【问题标题】:Move form relative to location clicked相对于单击的位置移动表单
【发布时间】:2013-05-12 06:36:59
【问题描述】:

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

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

【问题讨论】:

  • 只要适当处理WM_NCHITTEST 消息,Windows 就会为您完成所有窗口的移动。

标签: c# .net


【解决方案1】:

试试这个...

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

}

【讨论】:

  • 这行得通,但是当我生成我的边框时它会导致异常(我实际上是利用它来发挥我的优势,所以它很好),但是在表单被底部或右边距拖动后它停止工作.知道为什么吗?
  • 通过重置targetCell解决了这个问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-15
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
相关资源
最近更新 更多