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

标签 c# winforms

我试图限制表单在桌面上的移动位置。基本上我不希望他们能够将表格从桌面上移开。我发现了一堆 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; 
    }
  }
}

关于C# 想要限制表单可以移动到的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1885266/

相关文章:

c# - 如何使用 Get() 和 Set() 方法最小化一个类

c# - 当键从不冲突时快速并行添加到字典

C# - 在自定义位置显示与 winforms 控件关联的错误图标

c# - Nuget 组件缺失

c# - 为什么我收到错误 Cannot await 'void' ?

.net - 如何使 .NET 应用程序看起来像 Windows 8ish

c# - 如何以线程安全的方式关闭表单(从后台线程使用)?

c# - 好的 C# 面板界面组件?

c# - 网站中实体模型的命名空间

c# - 如何修复此 "circular reference"c#