WinForm限制窗体不能移到屏幕外的方法
本文实例讲述了WinForm限制窗体不能移到屏幕外的方法。分享给大家供大家参考。具体实现方法如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Drawing;
usingSystem.Runtime.InteropServices;
namespaceAppForm
{
///<summary>
///WinForm限制窗体不能移到屏幕外
///</summary>
publicclassFrmBase:Form
{
privatePoint_mouseDownPos;
privatebool_move;
protectedoverridevoidWndProc(refMessagem)
{
RECTnativeRect;
switch(m.Msg)
{
case0x20:
intlp=m.LParam.ToInt32();
if((lp&0xFFFF)==2&&
((lp>>0x10)&0xFFFF)==0x201)
{
_mouseDownPos=Control.MousePosition;
_move=true;
}
break;
case0x231:
if(_move)
{
Rectanglerect=Screen.GetWorkingArea(this);
nativeRect=newRECT(
_mouseDownPos.X-Location.X,
_mouseDownPos.Y-Location.Y,
rect.Right-(Bounds.Right-_mouseDownPos.X),
rect.Bottom-(Bounds.Bottom-_mouseDownPos.Y));
ClipCursor(refnativeRect);
}
break;
case0x0232:
if(_move)
{
nativeRect=newRECT(Screen.GetWorkingArea(this));
ClipCursor(refnativeRect);
_move=false;
}
break;
}
base.WndProc(refm);
}
[DllImport("user32.dll")]
publicstaticexternboolClipCursor(refRECTlpRect);
[StructLayout(LayoutKind.Sequential)]
publicstructRECT
{
publicintLeft;
publicintTop;
publicintRight;
publicintBottom;
publicRECT(intleft,inttop,intright,intbottom)
{
Left=left;
Top=top;
Right=right;
Bottom=bottom;
}
publicRECT(Rectanglerect)
{
Left=rect.Left;
Top=rect.Top;
Right=rect.Right;
Bottom=rect.Bottom;
}
publicRectangleRect
{
get
{
returnnewRectangle(
Left,
Top,
Right-Left,
Bottom-Top);
}
}
publicSizeSize
{
get
{
returnnewSize(Right-Left,Bottom-Top);
}
}
publicstaticRECTFromXYWH(intx,inty,intwidth,intheight)
{
returnnewRECT(x,
y,
x+width,
y+height);
}
publicstaticRECTFromRectangle(Rectanglerect)
{
returnnewRECT(rect.Left,
rect.Top,
rect.Right,
rect.Bottom);
}
}
}
}
希望本文所述对大家的C#程序设计有所帮助。