
.NET 1.1+Creating a Draggable Borderless Form (2)
For programs that require a non-standard interface, you can remove the borders of your forms. Once removed however, the user has no title bar to use to allow the form to be repositioned. This article describes how to allow dragging of a borderless form.
Adding the Events
The code to control the dragging operation must now be added to the form. The following three sections describe each of the three events that must be captured and processed.
MouseDown Event
The first event to add code to is the MouseDown event. This event is fired when the user initially depresses the mouse button. The event arguments include the current position of the mouse pointer relative to the form. This is simply stored in the offset variable. To indicate that dragging is in progress, the dragging flag is also set.
MouseMove Event
In the form's MouseMove event, the first thing to check is that the user is currently dragging. If the dragging flag is not set, no action takes place as this would cause inappropriate movement of the form. If the dragging flag is set, the current position of the mouse pointer is extracted from the event arguments. This is converted to an offset relative to the screen's origin using the PointToScreen method, which both accepts and returns a Point.
Now that the new location and the original offset are both known, the desired form location can be calculated by subtracting the X and Y co-ordinates of the original offset from the new screen location. The form can now be moved to the calculated position.
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (dragging)
{
Point currentScreenPos = PointToScreen(e.Location);
Location = new Point(currentScreenPos.X - offset.X, currentScreenPos.Y - offset.Y);
}
}
MouseUp event
The final event to capture is the MouseUp event that occurs when the user releases the mouse button. When this is fired, the dragging flag is cleared. This stops any further mouse movement from incorrectly repositioning the form.
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
dragging = false;
}
Testing the Program
The code is now complete. To test, execute the program and try dragging any part of the grey surface of the form.
31 July 2007