问题描述
我有一个WinForm应用程序,我正在尝试使用 MouseMove事件
在窗体中移动pictureBox,但是我不知道该怎么计算?在MouseMove上执行操作时,当我第一次使用pictureBox时,其位置会以无意义的方式更改,然后在移动pictureBox时位置会正确移动。
I have a WinForm application, I'm trying to move a pictureBox in a Form using MouseMove Event
, but i can't figure out what's the right calculation should i do on MouseMove, when i first the pictureBox , its location changes in a senseless way then on moving the pictureBox Location moves correctly.
这是面板名称 OuterPanel
,其中包含pictureBox picBox
,此处的代码im使用:
It's a Panel name OuterPanel
which contains the pictureBox picBox
, here the code im using :
private void picBox_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Point p = OuterPanel.PointToClient(MousePosition);
picBox.Location = this.PointToClient(p);
}
}
PS:目标是在放大后移动图像,像Windows照片查看器
P.S : the goal is moving image after zooming in, like windows photo viewer
更新: ConvertFromChildToForm
方法
private Point ConvertFromChildToForm(int x, int y,Control control)
{
Point p = new Point(x, y);
control.Location = p;
return p;
}
推荐答案
您必须管理三个事件使其正确完成:
You have to Manage three Events to get it done correctly :
-
MouseDown
-
MouseMove
-
MouseUp
MouseDown
MouseMove
MouseUp
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
方法
这篇关于如何在运行时在mousemove上移动控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!