FCI-Helwan blog

Just another FCI-H weblog

How to make your controls moveable?

Q: How to make your controls moveable?


A: Some people need to add style to their controls to be moveable that’s users can drag and drop them anywhere on the form.So, when user presses on a control and moves the mouse; control location should equal mouse axis.

Some variables used in our code.

/// <summary>
/// Indicates whether control is pressed by mouse or not
/// </summary>
bool IsDraged = false;

/// <summary>
/// Holds the X-coordinate of the control
/// </summary>
int Control_X = 0;

/// <summary>
/// Holds the Y-coordinate of the control
/// </summary>
int Control_Y = 0;

This is the mouse down event handler, we just checked the left button is pressed then set boolean variable IsDraged to true and assigned control location to mouse location.

private void Control_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
IsDraged = true;
Control_X = e.X;
Control_Y = e.Y;
}
}

Just when mouse left button released we set IsDraged to false.

private void Control_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
IsDraged = false;
}
}

Here’s when mouse moves while mouse left button not released yet, the computation used helps controls to move smoothly with the mouse movement.

private void Control_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Control active = (Control)sender;
if (IsDraged)
{
active.Left += e.X – Control_X / 12;
active.Top += e.Y – Control_Y / 12;
Control_X = e.X;
Control_Y = e.Y;
}
}
}

Advertisements

May 16, 2008 - Posted by | .NET Q and A, C#

5 Comments »

  1. Thanks a lot ramy.
    please continue you are from the best.

    gazak allah kol 5ir.

    Comment by Anonymous | May 25, 2008 | Reply

  2. Thank you a lot, Jazana ALLAH wy ayakom.

    Comment by Ramy Mahrous | May 25, 2008 | Reply

  3. hey ….very great post!

    But….Why do you split the previous position by 12?

    Comment by #Pinda# | May 8, 2009 | Reply

  4. As I said “the computation used helps controls to move smoothly with the mouse movement.”
    12 is just a number when I use it lets the controls move smoothly.

    Comment by Ramy Mahrous | May 8, 2009 | Reply

  5. nice one.. keep it up.

    Comment by harry | September 3, 2009 | Reply


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: