[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Make a transparent form and let the user move it in C#


To make a transparent form, set the form's TransparencyKey property to the same color as the form's BackColor.

If you like, you can give the form a BackgroundImage containing the color. However if you do, be sure to use a png, bmp, or some other format that produces exact colors. If you use a jpg, for example, the colors won't be exactly the same as the TransparencyKey color so they won't be transparent even if they look like the same color to the eye.

To avoid weird border and title bar effects, set the form's FormBorderStyle property to None.

That makes the form transparent but because the title bar is gone, the user cannot move it. To let the user move the form, use the WndProc method in whatever event you want to use to start the move. The following code uses the form's MouseDown event.

// On mouse down, start moving the form. private void Form1_MouseDown(object sender, MouseEventArgs e) { const int WM_NCLBUTTONDOWN = 0xA1; const int HT_CAPTION = 0x2; this.Capture = false; Message msg = Message.Create(this.Handle, WM_NCLBUTTONDOWN, (IntPtr)HT_CAPTION, IntPtr.Zero); WndProc(ref msg); }

When the user presses the mouse down on the form, the form captures the mouse. This code starts by setting this.Capture = false to release that capture. It then creates a Message structure representing the WM_NCLBUTTONDOWN message, which indicates that a button was pressed in the form's non-client area (NCL). The parameter HT_CAPTION indicates that the button was pressed on the form's caption area or title bar.

The program then calls the form's WndProc method to make the form process the message. That start a form drag just as if the user had pressed the mouse down on the form's title bar. (Even though in this example I removed the title bar.)

You can make special areas that the user has to click to move the form if you like. You can also add special areas to minimize, maximize, and close the form (the standard areas are removed with the FormBorderStyle = None).

Note that the user can still use Alt+F4 to close the form even though the close button is gone.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.