Title: Move a form without a title bar in C#
When the user presses the mouse down over the green lblMoveForm Label in the form's upper right corner, the following event handler executes.
// On left button, let the user drag the form.
private void lblMoveForm_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
// Release the mouse capture started by the mouse down.
lblMoveForm.Capture = false;
// Create and send a WM_NCLBUTTONDOWN message.
const int WM_NCLBUTTONDOWN = 0x00A1;
const int HTCAPTION = 2;
Message msg =
Message.Create(this.Handle, WM_NCLBUTTONDOWN,
new IntPtr(HTCAPTION), IntPtr.Zero);
this.DefWndProc(ref msg);
}
}
The code sets the control's Capture property to false to release the mouse capture that was started by pressing the mouse button down.
Next the program makes a Message with message WM_NCLBUTTONDOWN and wParam set to HTCAPTION, and calls the form's DefWndProc method to process the message. This is the same message Windows sends to the form when the user presses the mouse down over the form's title bar so it starts a form move. The rest is automatic. As far as the form is concerned, the user is dragging the form's title bar to move the form.
Download the example to experiment with it and to see additional details.
|