c# - 相对于单击的位置移动表单

标签 c# .net

我有一个表单,当用户单击并拖动边框区域时可以移动该表单。我见过的实现都是锁定当前鼠标位置,这样当移动窗体时,窗体会跳转,使鼠标位于左上角。我想更改它,使其行为类似于普通的 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/

相关文章:

c# - 如何使用 LINQ to XML 获取属性值?

c# - 为什么我要在 Equals 覆盖中执行 object.ReferenceEquals(null, this) ?

python - COMException从Plex插件访问WMP(使用Python for .NET)

c# - Web API 和 OData - 传递多个参数

c# - Wix-如何将目录复制到安装文件夹

c# - 使用 FSharp.Data 将 Web 应用程序部署到 Azure 网站

c# - 为什么属性不能是只读的?

c# - ClosedXML.Excel 中的自动调整列

C# Automapper 在 Null 时忽略属性

.net - 如何在 Windows 8/RT xaml 中显示消息框?