Moving a control by dragging it with the mouse in C#

后端 未结 3 1977
南旧
南旧 2020-12-08 16:47

I\'m trying to move the control named pictureBox1 by dragging it around. The problem is, when it moves, it keeps moving from a location to another location around the mouse,

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 17:20

    All you need:

    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;
            }
        }
    
    }
    

提交回复
热议问题