c# - 通过鼠标移动控件

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

关于c# - 通过鼠标移动控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4935291/

相关文章:

c# - 如何将项目添加到 IEnumerable SelectListItem

c# - ASP.Net 模式不显示

c# - 将收到的对象转换为 List<object> 或 IEnumerable<object>

c# - 国际奥委会 : How to create objects dynamically

c# - 强制 MySQL Connector.NET 返回一个 bool 值

c# - 要求所有参数和所有参数命名的类构造函数

c# - 'Newtonsoft.Json.. .' exists in both ' Blend\Newtonsoft.Json.dll' 和 'Solution\packages\...\

c# - 为什么当有后台线程运行时我可以停止 IHostedService?

c# - 并登录 LinkLabel 文本

javascript - 使用 C# 从服务器端打开页面加载事件的模态弹出窗口