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

时间:2009-12-11 01:19:52

标签: c# winforms

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

4 个答案:

答案 0 :(得分:5)

我意识到你不再对答案感兴趣,无论如何我都会发布一个解决方案。您想要处理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; 
    }
  }
}

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

我刚刚制作并覆盖了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);
        }
    }