簡體   English   中英

如何在C#中移動PictureBox?

[英]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結構變量。 移動控件后需要更改鼠標光標的相對位置。

你必須做幾件事

  1. MouseDown注冊移動操作的開始並記住鼠標的起始位置。

  2. MouseMove查看您是否正在移動圖片。 通過在圖片框的左上角保持相同的偏移來移動,即在移動時,鼠標指針應始終指向圖片框內的同一點。 這使得圖片框與鼠標指針一起移動。

  3. 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM