前言 |
贴边隐藏,像腾讯QQ一样拖到屏幕最上方就自己隐藏了,实现这个功能的办法有很多,可能我这个方法比较笨,毕竟能力有限。下图所示:
代码实现 |
首先我们要有一个定时器,设置一个较短的时间间隔,去检测窗体的位置,代码如下:
int sideThickness = 4;//边缘的厚度,窗体停靠在边缘隐藏后留出来的可见部分的厚度
//如果窗体最小化或最大化了则什么也不做
if (this.WindowState == FormWindowState.Minimized || this.WindowState == FormWindowState.Maximized)
{
return;
}
//如果鼠标在窗体内
if (Cursor.Position.X >= this.Left && Cursor.Position.X < this.Right && Cursor.Position.Y >= this.Top && Cursor.Position.Y < this.Bottom)
{
//如果窗体离屏幕边缘很近,则自动停靠在该边缘
if (this.Top <= sideThickness)
{
this.Top = 0;
}
if (this.Left <= sideThickness)
{
this.Left = 0;
}
if (this.Left >= Screen.PrimaryScreen.WorkingArea.Width - this.Width - sideThickness)
{
this.Left = Screen.PrimaryScreen.WorkingArea.Width - this.Width;
}
}
//当鼠标离开窗体以后
else
{
//隐藏到屏幕左边缘
if (this.Left == 0)
{
this.Left = sideThickness - this.Width;
}
//隐藏到屏幕右边缘
else if (this.Left == Screen.PrimaryScreen.WorkingArea.Width - this.Width)
{
this.Left = Screen.PrimaryScreen.WorkingArea.Width - sideThickness;
}
//隐藏到屏幕上边缘
else if (this.Top == 0 && this.Left > 0 && this.Left < Screen.PrimaryScreen.WorkingArea.Width - this.Width)
{
this.Top = sideThickness - this.Height;
}
}
这个效果是一下子消失了,如果你想让你的程度,缓缓的上去,可以加上这段代码
for (int i = 0; i <= this.Height; i++)
{
Point p = new Point(this.Location.X, this.Location.Y + i);//弹出框向下移动消失
this.PointToScreen(p);//即时转换成屏幕坐标
this.Location = p;// new Point(this.Location.X, this.Location.Y + 1);
System.Threading.Thread.Sleep(10);//下降速度调节,数字越小消失的速度越快,建议不大于10
}
总结 |
小小的功能,却有很强的逻辑思维在里面。所以呢,撸起袖子,继续干吧!