移动无边框Winform按住鼠标右键,可能使用本机方法
我有一种情况,我想通过在其客户区域上按住鼠标右键来移动窗体; 正如我所说,这种forms是无国界的。
我想“本地”移动它(如果可能的话,否则其他答案也可以)。 我的意思是当你在标题栏上按住鼠标左键时它的行为方式(鼠标移动和类似的东西,我得到很多奇怪的行为,但也许只是我)。
我已经阅读了很多内容,这篇文章看起来很有帮助
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/b9985b19-cab5-4fba-9dc5-f323d0d37e2f/
我尝试了各种方式来使用它,并通过http://msdn.microsoft.com/en-us/library/ff468877%28v=VS.85%29.aspx观看以寻找其他有用的东西,WM_NCRBUTTONDOWN出现在我的脑海中, wndproc没有检测到它,也许是因为它是由表单处理的?
任何建议都表示赞赏,谢谢
弗朗切斯科
public partial class DragForm : Form { // Offset from upper left of form where mouse grabbed private Size? _mouseGrabOffset; public DragForm() { InitializeComponent(); } protected override void OnMouseDown(MouseEventArgs e) { if( e.Button == System.Windows.Forms.MouseButtons.Right ) _mouseGrabOffset = new Size(e.Location); base.OnMouseDown(e); } protected override void OnMouseUp(MouseEventArgs e) { _mouseGrabOffset = null; base.OnMouseUp(e); } protected override void OnMouseMove(MouseEventArgs e) { if (_mouseGrabOffset.HasValue) { this.Location = Cursor.Position - _mouseGrabOffset.Value; } base.OnMouseMove(e); } }
你需要两个P / Invoke方法才能完成这项工作。
[DllImport("user32.dll")] static extern int SendMessage(IntPtr hwnd, int msg, int wparam, int lparam); [DllImport("user32.dll")] static extern bool ReleaseCapture();
几个常数:
const int WmNcLButtonDown = 0xA1; const int HtCaption= 2;
处理表单上的MouseDown
事件,然后执行以下操作:
private void Form_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { ReleaseCapture(); SendMessage(this.Handle, WmNcLButtonDown, HtCaption, 0); } }
这将发送您的表单与鼠标单击并按住标题区域时收到的相同事件。 移动鼠标,窗口移动。 松开鼠标按钮时,移动停止。 很容易。