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;
}
}
}
6 comments:
Thanks a lot ramy.
please continue you are from the best.
gazak allah kol 5ir.
Thank you a lot, Jazana ALLAH wy ayakom.
hey ....very great post!
But....Why do you split the previous position by 12?
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.
Nice post. I understand the logic behind it but I am a newbie to C#.
So in case if I would like to move a label using these commands, how ould I do it?
Drag the label on the form, from its properties assign its MouseDown handler to Control_MouseDown, MouseUp to Control_MouseUp, and MouseMove to Control_MouseMove, don't change anything in the code it'll work fine enshaa'Allah
Post a Comment