Subscribe

RSS Feed (xml)

Make a Borderless Form Movable

Borderless forms omit a title bar, which makes it impossible for a user to move them. You can compensate for this shortcoming by adding a control to the form that serves the same purpose. For example, below figure shows a form that includes a label to support dragging. The user can click this label, and then drag the form to a new location on the screen while holding down the mouse button. As the user moves the mouse, the form is automatically moved correspondingly, as though it's "attached" to the mouse pointer.

movable.JPG

To implement this solution, you need take the following steps:

  1. Create a form-level Boolean variable that tracks whether or not the form is currently being dragged.

  2. When the label is clicked, the code sets the flag to indicate that the form is in drag mode. At the same time, the current mouse position is recorded. You add this logic to the event handler for the Label.MouseDown event.

  3. When the user moves the mouse over the label, the form is moved correspondingly so that the position of the mouse over the label is unchanged. You add this logic to the event handler for the Label.MouseMove event.

  4. When the user releases the mouse button, the dragging mode is switched off. You add this logic to the event handler for the Label.MouseUp event.

Here's the complete form code:

using System;
using System.Windows.Forms;
using System.Drawing;

public class DragForm : System.Windows.Forms.Form {

    // (Designer code omitted.)

    // Tracks whether the form is in drag mode. If it is, mouse movements
    // over the label will be translated into form movements.
    private bool dragging;

    // Stores the offset where the label is clicked.
    private Point pointClicked;

    private void lblDrag_MouseDown(object sender,
      System.Windows.Forms.MouseEventArgs e) {
    
        if (e.Button == MouseButtons.Left) {
        
            dragging = true;
            pointClicked = new Point(e.X, e.Y);
        }
        else {
        
            dragging = false;
        }
    }

    private void lblDrag_MouseMove(object sender,
      System.Windows.Forms.MouseEventArgs e) {
    
        if (dragging) {
        
            Point pointMoveTo;

            // Find the current mouse position in screen coordinates.
            pointMoveTo = this.PointToScreen(new Point(e.X, e.Y));

            // Compensate for the position the control was clicked.
            pointMoveTo.Offset(-pointClicked.X, -pointClicked.Y);

            // Move the form.
            this.Location = pointMoveTo;
        }   
    }

    private void lblDrag_MouseUp(object sender,
      System.Windows.Forms.MouseEventArgs e) {
    
        dragging = false;
    }

    private void cmdClose_Click(object sender, System.EventArgs e) {
    
        this.Close();
    }
}

Technorati :

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail