1. 程式人生 > >【C#】-應用程式實現貼邊隱藏

【C#】-應用程式實現貼邊隱藏

前言

貼邊隱藏,像騰訊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
}

總結

小小的功能,卻有很強的邏輯思維在裡面。所以呢,擼起袖子,繼續幹吧!