how to move a control on mousemove in runtime?

拥有回忆 提交于 2019-11-29 12:51:45
Writwick

You have to Manage three Events to get it done correctly :

  • MouseDown
  • MouseMove
  • MouseUp

Here is a Related SO Question..

Your Code for picBox :

private void picBox_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        Point p = ConvertFromChildToForm(e.X, e.Y, picBox);
        iOldX = p.X;
        iOldY = p.Y;
        iClickX = e.X;
        iClickY = e.Y;
        clicked = true;
    }
}

private void picBox_MouseMove(object sender, MouseEventArgs e)
{
    if (clicked)
    {
        Point p = new Point(); // New Coordinate
        p.X =  e.X + picBox.Left;
        p.Y =  e.Y + picBox.Top;
        picBox.Left = p.X - iClickX;
        picBox.Top = p.Y - iClickY;
    }
}

private void picBox_MouseUp(object sender, MouseEventArgs e)
{
    clicked = false;   
}

private Point ConvertFromChildToForm(int x, int y, Control control)
{
    Point p = new Point(x, y);
    control.Location = p;
    return p;
}

ConvertFromChildToForm method from Mur Haf Soz

with use

ControlMoverOrResizer

class in this article you can do movable and resizable control in run time just with a line of code! :) example:

ControlMoverOrResizer.Init(button1);   

and now button1 is a movable and resizable control!

Try this. It's beautiful.

const uint WM_NCLBUTTONDOWN = 161;
const uint HTCAPTION = 2;

[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr window, uint message, IntPtr wParam, IntPtr lParam);

public Form1()
{
    PictureBox picBox = new PictureBox();
    picBox.Text = "this control is crazy!";
    picBox.BackColor = Color.Red;
    picBox.SetBounds(8, 8, 128, 64);
    picBox.MouseDown += OnMouseDown;
    Controls.Add(picBox);
}

private void OnMouseDown(object sender, MouseEventArgs e)
{
    ReleaseCapture();
    SendMessage((sender as Control).Handle, WM_NCLBUTTONDOWN, (IntPtr) HTCAPION, IntPtr.Zero);
}

The catch is only that you have to work with WinApi. And it won't let labels move. Dunno why.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!