的WinForms - 点击/形式的任何地方拖动来移动它,如果点击在窗体标题窗体、拖动、形式、标题

2023-09-02 10:28:16 作者:放你去浪

我创建了用于WinForms应用程序的小模态形式。它基本上是各种各样的进度条。不过,我想用户可以单击任意位置的形式,将其拖动它仍然在显示时移动它在桌面上。

I am creating a small modal form that is used in Winforms application. It is basically a progress bar of sorts. But I would like the user to be able to click anywhere in the form and drag it to move it around on the desktop while it is still being displayed.

我怎样才能实现这一行为?

How can I implement this behavior?

推荐答案

微软知识库文章320687 都有详细的回答了这个问题。

Microsoft KB Article 320687 has a detailed answer to this question.

基本上,你重写WndProc方法返回HTCAPTION当被测点的WM_NCHITTEST消息是在窗体的客户区域 - 这实际上是,告诉Windows来对待单击完全一样,如果它曾经发生在窗体的标题。

Basically, you override the WndProc method to return HTCAPTION to the WM_NCHITTEST message when the point being tested is in the client area of the form -- which is, in effect, telling Windows to treat the click exactly the same as if it had occured on the caption of the form.

private const int WM_NCHITTEST = 0x84;
private const int HTCLIENT = 0x1;
private const int HTCAPTION = 0x2;

protected override void WndProc(ref Message m)
{
  switch(m.Msg)
  {
    case WM_NCHITTEST:
      base.WndProc(ref m);
      if ((int)m.Result == HTCLIENT)
      {
        m.Result = (IntPtr)HTCAPTION;
      }

      return;
  }

  base.WndProc(ref m);
}