通过在C#中用鼠标拖动来移动控件 [英] Moving a control by dragging it with the mouse in C#

查看:437
本文介绍了通过在C#中用鼠标拖动来移动控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过拖动来移动名为pictureBox1的控件.问题是,当它移动时,它会不断从一个位置移动到鼠标周围的另一个位置,但是它确实跟随它移动... 这是我的代码.如果您能帮助我,我将不胜感激

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, but it does follow it... This is my code. and I would really appreciate it if you could help me

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

}

推荐答案

所有您需要的东西:

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

}

这篇关于通过在C#中用鼠标拖动来移动控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆