gpt4 book ai didi

c# - 通过鼠标移动控件

转载 作者:行者123 更新时间:2023-12-05 08:19:22 24 4
gpt4 key购买 nike

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

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com