C# 如何将windows窗体按钮拖动到特定点,但仅在检查新点的位置之后?
我想允许用户根据用户拖动按钮的方向将按钮拖动到右+X或左-X点。我是windows窗体的新手,希望您能浏览一下。在我的示例中,我硬编码了10像素的新位置增量,但我希望用户能够将按钮拖动到他想要的地方。 以下是我当前的代码:C# 如何将windows窗体按钮拖动到特定点,但仅在检查新点的位置之后?,c#,.net,winforms,C#,.net,Winforms,我想允许用户根据用户拖动按钮的方向将按钮拖动到右+X或左-X点。我是windows窗体的新手,希望您能浏览一下。在我的示例中,我硬编码了10像素的新位置增量,但我希望用户能够将按钮拖动到他想要的地方。 以下是我当前的代码: public partial class Form1 : Form { public Form1() { InitializeComponent(); Load +=Form1_Load; } privat
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Load +=Form1_Load;
}
private void Form1_Load(object sender, EventArgs e)
{
}
bool isDragged = false;
private void button1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isDragged = true;
}
else
{
isDragged = false;
}
}
private void button1_MouseMove(object sender, MouseEventArgs e)
{
if (isDragged)
{
button1.Location = new Point(button1.Location.X + 10, button1.Location.Y);
}
isDragged = false;
}
}
试试这个:
private Point mouseDown, buttonLocation;
private bool isDragged = false;
private void button1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isDragged = true;
mouseDown = Cursor.Position;
buttonLocation = button1.Location;
}
}
private void button1_MouseMove(object sender, MouseEventArgs e)
{
if (isDragged)
{
button1.Location = new Point(buttonLocation.X + (Cursor.Position.X - mouseDown.X), button1.Location.Y);
}
}
private void button1_MouseUp(object sender, MouseEventArgs e)
{
isDragged = false;
}
您可以在这里尝试解决方案按钮仍然只是以任何方式移动一滴,而不是拖动的长度。@MirrorEyes它对我来说移动得很好。