AlaaShaker's Weblog

// untitled …

Moving Controls Around with the Mouse

leave a comment »

Cursor_Wallpaper__by_Warpig It happens a lot when you want to build a custom control that the user can move around in your form with the mouse, or even move around the entire form over the desktop (as Windows Live Messenger chat windows).

So, I thought of sharing this code snippet that does that for you ..

#region Mouse Move Code

private Point prevPoint = new Point(0, 0);
private bool isMouseDown = false;

protected override void OnMouseDown(MouseEventArgs e)
{
    base.OnMouseDown(e);
    if (e.Button == MouseButtons.Left)
    {
        isMouseDown = true;
        prevPoint = Control.MousePosition;
    }
}
protected override void OnMouseUp(MouseEventArgs e)
{
    base.OnMouseUp(e);
    if(isMouseDown)
        isMouseDown = false;
}
protected override void OnMouseMove(MouseEventArgs e)
{
    base.OnMouseMove(e);

    if (isMouseDown)
    {
        int xDiff = Control.MousePosition.X - prevPoint.X;
        int yDiff = Control.MousePosition.Y - prevPoint.Y;
        this.Location = new Point(this.Location.X + xDiff, this.Location.Y + yDiff);
        prevPoint = new Point(Control.MousePosition.X, Control.MousePosition.Y);
    }
}
#endregion

Place this code in the source-code file of any custom control you build, and watch it move around with your mouse on the form. If you want to move the whole form, then place it in the form’s source-code file, and change this.Location to this.DesktopLocation and that should do it.


How it works?
Once the user clicks the control, a flag isMouseDown is raised, and the mouse position is saved. As the mouse moves, if the flag is raised (i.e. the user has the mouse button down), the difference in the mouse position is calculated, the control is translated with that difference, then the new location is saved and so on. Finally, when the user lifts up the mouse button, the flag is set to false freeing the control.

Advice: With rich GUI applications, it’s advised to set the form’s DoubleBuffered property to true, to prevent the flickering.

Advertisements

Written by AlaaShaker

May 16, 2008 at 5:49 pm

Posted in Development

Tagged with , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: