Creating a Draggable, Borderless Windows Form
Designing borderless forms in Windows Forms offers a sleek, modern aesthetic. However, this often presents a challenge: how to make the form movable without the usual title bar or border? This article provides a solution using the Windows API.
The key is to simulate a click on the title bar using the SendMessage
and ReleaseCapture
functions. These API calls effectively trick the window manager into initiating a drag operation, even in the absence of a visible border.
Here's the code implementation:
<code class="language-csharp">public const int WM_NCLBUTTONDOWN = 0xA1; public const int HT_CAPTION = 0x2; [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool ReleaseCapture(); private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { if (e.Button == MouseButtons.Left) { ReleaseCapture(); SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0); } }</code>
Adding this code to your form's MouseDown
event handler allows you to drag and reposition the borderless form by clicking and dragging anywhere within the form's client area. This provides the desired functionality without compromising the clean, borderless design.
The above is the detailed content of How Can I Make a Borderless Form Movable in Windows Forms?. For more information, please follow other related articles on the PHP Chinese website!