[英]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.