C#希望限制可以将表单移动到的位置 [英] C# want to restrict where a form can be moved to

查看:29
本文介绍了C#希望限制可以将表单移动到的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to restrict where a form can be moved to on the desktop. Basically I don't want them to be able to move the form off the desktop. I found a bunch of SetBounds functions but they seem to do something that seems very odd to me for the names of the functions and aren't serving my purpose.

推荐答案

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

I realize you are not interested in an answer anymore, I'll post a solution anyway. You want to handle the WM_MOVING message and override the target position. Beware that it has side-effects on Win7 and is inadvisable if the user has more than one monitor. Mouse position handling isn't great either. The code:

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#希望限制可以将表单移动到的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆