C#中实现窗口靠近屏幕边缘,自动吸附。
转载:https://blog.csdn.net/qq_35831134/article/details/88751067
new bool Hide = false; //用来表示当前隐藏状态,例如Hide=false就是 不在隐藏状态
string type = ""; //用来表示窗口隐藏在哪个方向
private void Timer2_Tick(object sender, EventArgs e) //定时器2 timer2_Tick函数
{
//this.TopMost = false; //窗体不显示在所有软件最前面
Point pt = new Point(Form.MousePosition.X, Form.MousePosition.Y);//获得当前鼠标位置
Screen screen = Screen.PrimaryScreen;
int width = screen.Bounds.Width; //获取屏幕的宽度
int height = screen.Bounds.Height; //获取屏幕的高度
if (!this.Bounds.Contains(pt)) //判断鼠标是否在窗体内
{ //如果不在窗体内
if (Hide == false)
{
if (this.Location.X < 10) //窗口左边碰到屏幕最左边
{
this.Left = -this.Width + 3; //隐藏窗口,窗口宽度加3取反(为负数)
Hide = true;
type = "left"; //窗口隐藏在左边
}
else if (width - this.Location.X - this.Width < 10)//窗口右边碰到屏幕最右边
{
this.Left = width - 3; //隐藏窗口,窗口宽度加3取反(为负数)
Hide = true;
type = "right"; //窗口隐藏在右边
}
else if (this.Location.Y < 10) //窗口上边碰到屏幕最上边
{
this.Top = -this.Height + 3; //隐藏窗口,窗口高度加3取反(为负数)
Hide = true;
type = "up"; //窗口隐藏在上边
}
}
}
else
{ //如果在窗体内
if (this.Location.X > 20 && type == "left")
{
Hide = false;
}
else if (width - this.Location.X - this.Width > 20 && type == "right")
{
Hide = false;
}
else if (this.Location.Y > 20 && type == "up")
{
Hide = false;
}
//如果在窗体内且之前是隐藏状态
if (Hide == true)
{
this.TopMost = true; //窗体显示在所有软件最前面
if (type == "left")
{
this.Left = 0;
Hide = false;
}
else if (type == "right")
{
this.Left = width - this.Width;
Hide = false;
}
else if (type == "up")
{
this.Top = 0;
Hide = false;
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
timer2.Interval = 1;//1毫秒
timer2.Start(); //启动定时器2
}