c# - 通过鼠标移动控件

我打算用鼠标移动按钮,一切正常,但是当我在按钮窗口上移动鼠标时,按钮的左侧和顶部(左上角)将位于光标位置。

我不希望这种情况发生。我的代码中的错误在哪里?

private void button1_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.Left)
    {
        clicked = true;
    }

}

private void button1_MouseMove(object sender, MouseEventArgs e)
{
    if (clicked)
    {
        Point p = new Point();//in form coordinates
        p.X =  e.X + button1.Left;
        p.Y =  e.Y + button1.Top;
        button1.Left = p.X;
        button1.Top = p.Y ;

    }

}

private void button1_MouseUp(object sender, MouseEventArgs e)
{
    clicked = false;   
}

最佳答案

这就是你需要的一切

    private Point MouseDownLocation;

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

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

https://stackoverflow.com/questions/4935291/

相关文章:

php - 瑞士的语言环境(正确显示瑞士法郎)

asp.net - 使用 Windows 身份验证,但被重定向到表单例份验证登录页面?

xcode - 在界面生成器中将标签旋转为横向

shell - 在 unix shell 脚本中用空格替换换行符

vb.net - 计算visual basic中两个日期之间的工作日数

c# - 如何从列表框 C# 中删除选定的项目

php - 重载 PHP die() 函数

php - echo $_SESSION 然后取消设置

perl - 在 perl 中基于散列中的值进行排序的简单方法

python - Tkinter 输入字符限制