欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WinForm限制窗体不能移到屏幕外的方法

程序员文章站 2023-11-30 10:20:10
本文实例讲述了winform限制窗体不能移到屏幕外的方法。分享给大家供大家参考。具体实现方法如下: using system; using system.col...

本文实例讲述了winform限制窗体不能移到屏幕外的方法。分享给大家供大家参考。具体实现方法如下:

using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.windows.forms;
using system.drawing;
using system.runtime.interopservices;
namespace appform
{
 /// <summary>
 /// winform限制窗体不能移到屏幕外
 /// </summary>
 public class frmbase : form
 {
 private point _mousedownpos;
 private bool _move;
 protected override void wndproc(ref message m)
 {
  rect nativerect;
  switch (m.msg)
  {
  case 0x20:
   int lp = m.lparam.toint32();
   if ((lp & 0xffff) == 2 &&
   ((lp >> 0x10) & 0xffff) == 0x201)
   {
   _mousedownpos = control.mouseposition;
   _move = true;
   }
   break;
  case 0x231:
   if (_move)
   {
   rectangle rect = screen.getworkingarea(this);
   nativerect = new rect(
    _mousedownpos.x - location.x,
    _mousedownpos.y - location.y,
    rect.right - (bounds.right - _mousedownpos.x),
    rect.bottom - (bounds.bottom - _mousedownpos.y));
   clipcursor(ref nativerect);
   }
   break;
  case 0x0232:
   if (_move)
   {
   nativerect = new rect(screen.getworkingarea(this));
   clipcursor(ref nativerect);
   _move = false;
   }
   break;
  }
  base.wndproc(ref m);
 }
 [dllimport("user32.dll")]
 public static extern bool clipcursor(ref rect lprect);
 [structlayout(layoutkind.sequential)]
 public struct rect
 {
  public int left;
  public int top;
  public int right;
  public int bottom;
  public rect(int left, int top, int right, int bottom)
  {
  left = left;
  top = top;
  right = right;
  bottom = bottom;
  }
  public rect(rectangle rect)
  {
  left = rect.left;
  top = rect.top;
  right = rect.right;
  bottom = rect.bottom;
  }
  public rectangle rect
  {
  get
  {
   return new rectangle(
   left,
   top,
   right - left,
   bottom - top);
  }
  }
  public size size
  {
  get
  {
   return new size(right - left, bottom - top);
  }
  }
  public static rect fromxywh(int x, int y, int width, int height)
  {
  return new rect(x,
    y,
    x + width,
    y + height);
  }
  public static rect fromrectangle(rectangle rect)
  {
  return new rect(rect.left,
     rect.top,
     rect.right,
     rect.bottom);
  }
 }
 }
}

希望本文所述对大家的c#程序设计有所帮助。