110,538
社区成员
发帖
与我相关
我的任务
分享
using System.Runtime.InteropServices;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("user32.dll")]
public static extern IntPtr GetDesktopWindow();
protected override CreateParams CreateParams
{
get
{
const int WS_EX_TOPMOST = 8;
base.CreateParams.Parent = GetDesktopWindow();
base.CreateParams.ExStyle |= WS_EX_TOPMOST;
return base.CreateParams;
}
}
AnchorStyles anchors;
const int OFFSET = 2;
protected override void WndProc(ref Message m)
{
const int WM_MOVING = 534;
switch (m.Msg)
{
case WM_MOVING: // 窗体移动的消息,控制窗体不会移出屏幕外
int left = Marshal.ReadInt32(m.LParam, 0);
int top = Marshal.ReadInt32(m.LParam, 4);
int right =Marshal.ReadInt32(m.LParam, 8);
int bottom =Marshal.ReadInt32(m.LParam, 12);
left = Math.Min(Math.Max(0, left),
Screen.PrimaryScreen.Bounds.Width - Width);
top = Math.Min(Math.Max(0, top),
Screen.PrimaryScreen.Bounds.Height - Height);
right = Math.Min(Math.Max(Width, right),
Screen.PrimaryScreen.Bounds.Width);
bottom = Math.Min(Math.Max(Height, bottom),
Screen.PrimaryScreen.Bounds.Height);
Marshal.WriteInt32(m.LParam, 0, left);
Marshal.WriteInt32(m.LParam, 4, top);
Marshal.WriteInt32(m.LParam, 8, right);
Marshal.WriteInt32(m.LParam, 12, bottom);
anchors = AnchorStyles.None;
if (left <= OFFSET) anchors |= AnchorStyles.Left;
if (top <= OFFSET) anchors |= AnchorStyles.Top;
if (bottom >= Screen.PrimaryScreen.Bounds.Height - OFFSET)
anchors |= AnchorStyles.Bottom;
if (right >= Screen.PrimaryScreen.Bounds.Width - OFFSET)
anchors |= AnchorStyles.Right;
timer1.Enabled = anchors != AnchorStyles.None;
break;
}
base.WndProc(ref m);
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = false;
timer1.Interval = 200;
TopMost = true;
}
[DllImport("user32.dll")]
public static extern IntPtr WindowFromPoint(Point Point);
[DllImport("user32.dll")]
public static extern IntPtr GetParent(IntPtr hWnd);
private void timer1_Tick(object sender, EventArgs e)
{
IntPtr vHandle = WindowFromPoint(Control.MousePosition);
while (vHandle != IntPtr.Zero && vHandle != Handle)
vHandle = GetParent(vHandle);
if (vHandle == Handle) // 如果鼠标停留的窗体是本窗体,还原位置
{
if ((anchors & AnchorStyles.Left) == AnchorStyles.Left) Left = 0;
if ((anchors & AnchorStyles.Top) == AnchorStyles.Top) Top = 0;
if ((anchors & AnchorStyles.Right) == AnchorStyles.Right)
Left = Screen.PrimaryScreen.Bounds.Width - Width;
if ((anchors & AnchorStyles.Bottom) == AnchorStyles.Bottom)
Top = Screen.PrimaryScreen.Bounds.Height - Height;
}
else // 隐藏起来
{
if ((anchors & AnchorStyles.Left) == AnchorStyles.Left)
Left = -Width + OFFSET;
if ((anchors & AnchorStyles.Top) == AnchorStyles.Top)
Top = -Height + OFFSET;
if ((anchors & AnchorStyles.Right) == AnchorStyles.Right)
Left = Screen.PrimaryScreen.Bounds.Width - OFFSET;
if ((anchors & AnchorStyles.Bottom) == AnchorStyles.Bottom)
Top = Screen.PrimaryScreen.Bounds.Height - OFFSET;
}
}
}