直接上代碼:
1 [DllImport("User32.dll")]
2 public static extern bool PtInRect(ref Rectangle Rects, Point lpPoint);
3
4 private void timerShowHide_Tick(object sender, EventArgs e)
5 {
6 if (this.WindowState == FormWindowState.Normal)
7 {
8 System.Drawing.Point cursorPoint = new Point(Cursor.Position.X, Cursor.Position.Y);//擷取滑鼠在螢幕的座標點
9 Rectangle Rects = new Rectangle(this.Left, this.Top, this.Left + this.Width, this.Top + this.Height);//儲存當前表單在螢幕的所在地區
10 bool prInRect = PtInRect(ref Rects, cursorPoint);
11 if (prInRect)
12 {//當滑鼠在當前表單內
13 if (this.Top < 0)//表單的Top屬性小於0
14 this.Top = 0;
15 else if (this.Left < 0)//表單的Left屬性小於0
16 this.Left = 0;
17 else if (this.Right > Screen.PrimaryScreen.WorkingArea.Width)//表單的Right屬性大於螢幕寬度
18 this.Left = Screen.PrimaryScreen.WorkingArea.Width - this.Width;
19 }
20 else
21 {
22 if (this.Top < 5) //當表單的上邊框與螢幕的頂端的距離小於5時
23 this.Top = 5 - this.Height; //將表單隱藏到螢幕的頂端
24 else if (this.Left < 5) //當表單的左邊框與螢幕的左端的距離小於5時
25 this.Left = 5 - this.Width; //將表單隱藏到螢幕的左端
26 else if (this.Right > Screen.PrimaryScreen.WorkingArea.Width - 5)//當表單的右邊框與螢幕的右端的距離小於5時
27 this.Left = Screen.PrimaryScreen.WorkingArea.Width - 5;//將表單隱藏到螢幕的右端
28 }
29 }
30 }