C#想要限制表单可以移动到的位置

我试图限制表格可以移动到桌面上的位置。 基本上我不希望他们能够将表单移出桌面。 我发现了一堆SetBounds函数,但它们似乎做了一些对于函数名称来说似乎很奇怪的事情并没有达到我的目的。

我意识到你不再对答案感兴趣了,无论如何我都会发布一个解决方案。 您想要处理WM_MOVING消息并覆盖目标位置。 请注意,它在Win7上有副作用,如果用户有多个显示器,则不建议使用。 鼠标位置处理也不是很好。 代码:

using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } protected override void WndProc(ref Message m) { if (m.Msg == 0x216) { // Trap WM_MOVING RECT rc = (RECT)Marshal.PtrToStructure(m.LParam, typeof(RECT)); Screen scr = Screen.FromRectangle(Rectangle.FromLTRB(rc.left, rc.top, rc.right, rc.bottom)); if (rc.left < scr.WorkingArea.Left) {rc.left = scr.WorkingArea.Left; rc.right = rc.left + this.Width; } if (rc.top < scr.WorkingArea.Top) { rc.top = scr.WorkingArea.Top; rc.bottom = rc.top + this.Height; } if (rc.right > scr.WorkingArea.Right) { rc.right = scr.WorkingArea.Right; rc.left = rc.right - this.Width; } if (rc.bottom > scr.WorkingArea.Bottom) { rc.bottom = scr.WorkingArea.Bottom; rc.top = rc.bottom - this.Height; } Marshal.StructureToPtr(rc, m.LParam, false); } base.WndProc(ref m); } private struct RECT { public int left; public int top; public int right; public int bottom; } } } 

只需处理Move事件,或覆盖OnMove ,以确保窗口位于桌面中:

 protected override OnMove(EventArgs e) { if (Screen.PrimaryScreen.WorkingArea.Contains(this.Location)) { this.Location = Screen.PrimaryScreen.WorkingArea.Location; } } 

我认为,如果将表单边框样式设置为none,则无法移动该表单。

http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formborderstyle%28VS.71%29.aspx

我刚刚制作并覆盖了OnLocationChanged。 这很粗糙但很有效,我只允许有一天找到修复工具,所以我已经完成了。 表单的长度和宽度是544和312. OnMove和OnLocationChanged之间有什么区别?

 protected override void OnLocationChanged(EventArgs e) { if (this.Location.X > Screen.PrimaryScreen.WorkingArea.X + Screen.PrimaryScreen.WorkingArea.Width - 544) { this.SetBounds(0, 0, 544, 312); } else if(this.Location.X < Screen.PrimaryScreen.WorkingArea.X) { this.SetBounds(0, 0, 544, 312); } if (this.Location.Y > Screen.PrimaryScreen.WorkingArea.Y + Screen.PrimaryScreen.WorkingArea.Height - 312) { this.SetBounds(0, 0, 544, 312); } else if (this.Location.Y < Screen.PrimaryScreen.WorkingArea.Y) { this.SetBounds(0, 0, 544, 312); } }