1. private void timer1_Tick(object sender, EventArgs e)
    2. {
    3. timer1.Interval = 200;
    4. AutoSideHideOrShow();
    5. }
    6. void AutoSideHideOrShow()
    7. {
    8. int sideThickness = 2;//边缘的厚度,窗体停靠在边缘隐藏后留出来的可见部分的厚度
    9. //如果窗体最小化或最大化了则什么也不做
    10. if (this.WindowState == FormWindowState.Minimized || this.WindowState == FormWindowState.Maximized)
    11. {
    12. return;
    13. }
    14. //如果鼠标在窗体内
    15. if (Cursor.Position.X >= this.Left && Cursor.Position.X < this.Right && Cursor.Position.Y >= this.Top && Cursor.Position.Y < this.Bottom)
    16. {
    17. //如果窗体离屏幕边缘很近,则自动停靠在该边缘
    18. if (this.Top <= sideThickness)
    19. {
    20. this.Top = 0;
    21. }
    22. if (this.Left <= sideThickness)
    23. {
    24. this.Left = 0;
    25. }
    26. if (this.Left >= Screen.PrimaryScreen.WorkingArea.Width - this.Width - sideThickness)
    27. {
    28. this.Left = Screen.PrimaryScreen.WorkingArea.Width - this.Width;
    29. }
    30. }
    31. //当鼠标离开窗体以后
    32. else
    33. {
    34. //隐藏到屏幕左边缘
    35. if (this.Left == 0)
    36. {
    37. this.Left = sideThickness - this.Width;
    38. }
    39. //隐藏到屏幕右边缘
    40. else if (this.Left == Screen.PrimaryScreen.WorkingArea.Width - this.Width)
    41. {
    42. this.Left = Screen.PrimaryScreen.WorkingArea.Width - sideThickness;
    43. }
    44. //隐藏到屏幕上边缘
    45. else if (this.Top == 0 && this.Left > 0 && this.Left < Screen.PrimaryScreen.WorkingArea.Width - this.Width)
    46. {
    47. this.Top = sideThickness - this.Height;
    48. }
    49. }
    50. }