如何在运行时移动鼠标移动控件?

时间:2012-05-19 04:45:33

标签: c# winforms controls mousemove

我有一个WinForm应用程序,我正在尝试使用MouseMove Event在一个表单中移动一个pictureBox,但我无法弄清楚我应该在MouseMove上做什么是正确的计算,当我第一次使用pictureBox时,它的位置以无意义的方式改变,然后移动pictureBox位置正确移动。

这是一个面板名称OuterPanel,其中包含pictureBox picBox,此处代码即时使用:

private void picBox_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left)
    {
        Point p = OuterPanel.PointToClient(MousePosition);
        picBox.Location = this.PointToClient(p);
    }
}

P.S:目标是在放大后移动图像,例如windows photo viewer

enter image description here

更新ConvertFromChildToForm方法

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

3 个答案:

答案 0 :(得分:3)

您必须管理三个事件才能正确完成:

  • MouseDown
  • MouseMove
  • MouseUp

Here is a Related SO Question..

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;
}
来自Mur Haf Soz

ConvertFromChildToForm方法

答案 1 :(得分:0)

使用

  

ControlMoverOrResizer

this article中的

类,您只需使用一行代码就可以在运行时进行可移动和可调整大小的控制! :) 例如:

ControlMoverOrResizer.Init(button1);   

现在button1是一个可移动且可调整大小的控件!

答案 2 :(得分:0)

试试这个。它很美。

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);
}

捕获只是你必须使用WinApi。它不会让标签移动。不知道为什么。