我有一个表单,当用户单击并拖动边框区域时可以移动该表单。我见过的实现都是锁定当前鼠标位置,这样当移动窗体时,窗体会跳转,使鼠标位于左上角。我想更改它,使其行为类似于普通的 Windows 窗体,并且窗体在移动时相对于鼠标保持在相同的位置。我当前的代码如下所示:
Point locationClicked;
bool isMouseDown = false;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
isMouseDown = true;
locationClicked = new Point(e.Location.X, e.Location.Y);
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
isMouseDown = false;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (isMouseDown && targetCell == new Point(-1, -1) && (mouseLocation.X < margin.X || mouseLocation.Y < margin.Y ||
mouseLocation.X > margin.X + cellSize.Width * gridSize.Width ||
mouseLocation.Y > margin.Y + cellSize.Height * gridSize.Height))
{
this.Location = new Point(e.Location.X - locationClicked.X, e.Location.Y - locationClicked.Y);
}
}
当我拖动窗口时,它的行为与我想要的类似。表单在屏幕上的两个位置之间闪烁,其中一个位置的移动速度约为鼠标速度的一半。有什么办法可以解决这个问题吗?
最佳答案
试试这个...
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Point locationClicked;
bool dragForm = false;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
locationClicked = new Point(e.Location.X, e.Location.Y);
if (isMouseDown && targetCell == new Point(-1, -1) && (mouseLocation.X < margin.X || mouseLocation.Y < margin.Y ||
mouseLocation.X > margin.X + cellSize.Width * gridSize.Width ||
mouseLocation.Y > margin.Y + cellSize.Height * gridSize.Height))
{
dragForm = true;
}
}
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (dragForm)
{
this.Location = new Point(this.Location.X + (e.X - locationClicked.X), this.Location.Y + (e.Y - locationClicked.Y));
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
dragForm = false;
}
}
关于c# - 相对于单击的位置移动表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16500491/