-->

通过在C#鼠标拖动移动的控制(Moving a control by dragging it wit

2019-09-02 00:57发布

我试图通过拖动周围将名为pictureBox1控制。 问题是,当它移动时,它不断从位置移动到鼠标周围其他位置,但它确实遵循它...这是我的代码。 我真的很感激,如果你能帮助我

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    bool selected = false;
    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        selected = true;
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (selected == true)
        {
            pictureBox1.Location = e.Location;
        }
    }

    private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
    {
        selected = false;
    }

}

Answer 1:

一切你需要的:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }


    private Point MouseDownLocation;


    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            MouseDownLocation = e.Location;
        }
    }

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            pictureBox1.Left = e.X + pictureBox1.Left - MouseDownLocation.X;
            pictureBox1.Top = e.Y + pictureBox1.Top - MouseDownLocation.Y;
        }
    }

}


Answer 2:

尝试用小鼠在运行时移动PictureBox控件

 private void pictureBox7_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                xPos = e.X;
                yPos = e.Y;
            }
        }

        private void pictureBox7_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            PictureBox p = sender as PictureBox;

            if (p != null)
            {
                if (e.Button == MouseButtons.Left)
                {
                    p.Top += (e.Y - yPos);
                    p.Left += (e.X - xPos);
                }
            }

        }


文章来源: Moving a control by dragging it with the mouse in C#