2009-10-06 136 views
0

我有一个没有边框,标题栏,菜单等的Windows窗体。我希望用户能够按住CTRL键,左键单击表单上的任意位置并拖动它,移动。任何想法如何做到这一点?我想这一点,但它闪烁,不少:如何在按住鼠标的同时移动表单?

private void HiddenForm_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) 
    { 
     if (e.Button == System.Windows.Forms.MouseButtons.Left) 
     { 
      this.SuspendLayout(); 
      Point xy = new Point(this.Location.X + (e.X - this.Location.X), this.Location.Y + (e.Y - this.Location.Y)); 
      this.Location = xy; 
      this.ResumeLayout(true); 
     } 
    } 

回答

4

试试这个

using System.Runtime.InteropServices; 

const int HT_CAPTION = 0x2; 
const int WM_NCLBUTTONDOWN = 0xA1; 

[DllImportAttribute("user32.dll")] 
public static extern int SendMessage(IntPtr hWnd,int Msg, int wParam, int lParam); 
[DllImportAttribute("user32.dll")] 
public static extern bool ReleaseCapture();  


private void Form1_MouseDown(object sender, MouseEventArgs e) 
{ 
    if (e.Button == MouseButtons.Left) 
    { 
    ReleaseCapture(); 
    SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0); 
    } 
} 

更新

ReleaseCapture()函数释放从一个窗口在当前线程和恢复鼠标捕获正常的鼠标输入处理。捕获鼠标的窗口接收所有鼠标输入,而不管光标的位置如何,除非在另一个线程的窗口中单击鼠标按钮时鼠标按钮被点击。

当在窗口的非客户区域上进行鼠标左键单击时,WM_NCLBUTTONDOWN消息被发送到窗口。 wParam指定了命中测试枚举值。我们通过了HTCAPTION,并且lParam指定了光标位置,我们将其作为0传递,以确保它位于标题栏中。

+0

这很好,只是好奇它在做什么? – esac 2009-10-06 23:35:47

+0

它是在默认的窗口过程中,在窗口的“标题”非客户区发生鼠标停止事件。 尽管如果你想要正确的实现,你应该添加你自己的消息处理钩子并且处理WM_NCHITTEST消息来返回HT_CAPTION你想要启用表单拖动的窗体区域。 – 2009-10-07 00:01:06

+0

+1甜蜜......你赢了:)我甚至没有得到正确的数学LOL。 – 2009-10-07 00:59:03

相关问题