[英]How to move PictureBox in C#?
我已经使用此代码在pictureBox_MouseMove
事件上移动图片框
pictureBox.Location = new System.Drawing.Point(e.Location);
但是当我试图执行图片框闪烁时,无法识别确切的位置。 你们可以帮助我吗? 我希望图片框稳定......
您想要按鼠标移动的数量移动控件:
Point mousePos;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e) {
mousePos = e.Location;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) {
int dx = e.X - mousePos.X;
int dy = e.Y - mousePos.Y;
pictureBox1.Location = new Point(pictureBox1.Left + dx, pictureBox1.Top + dy);
}
}
请注意,这个代码不更新的MouseMove的mousePos结构变量。 移动控件后需要更改鼠标光标的相对位置。
你必须做几件事
在MouseDown
注册移动操作的开始并记住鼠标的起始位置。
在MouseMove
查看您是否正在移动图片。 通过在图片框的左上角保持相同的偏移来移动,即在移动时,鼠标指针应始终指向图片框内的同一点。 这使得图片框与鼠标指针一起移动。
在MouseUp
注册移动操作的结束。
private bool _moving;
private Point _startLocation;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
_moving = true;
_startLocation = e.Location;
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
_moving = false;
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (_moving) {
pictureBox1.Left += e.Location.X - _startLocation.X;
pictureBox1.Top += e.Location.Y - _startLocation.Y;
}
}
尝试将SizeMode
属性从AutoSize
更改为Normal
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.