如何在C#中移动PictureBox
本文关键字:移动 PictureBox | 更新日期: 2023-09-27 18:28:26
我已使用此代码移动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