2

我有一个表单,当用户在边框区域中单击并拖动时,它可以移动。我见过的实现都锁定到当前鼠标位置,所以当窗体移动时,窗体会跳转,使鼠标位于左上角。我想对其进行更改,使其表现得像一个普通的 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);
    }
}

当我拖动窗口时,它的行为与我想要的相似。表格在屏幕上的两个位置之间闪烁,其中一个位置的移动速度约为鼠标速度的一半。有没有办法解决这个问题?

4

1 回答 1

3

Try this out...

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

}
于 2013-05-11T20:29:12.997 回答