1. using System.Windows.Forms;
    2. namespace ServerApp
    3. {
    4. /// <summary>
    5. /// MainWindow.xaml 的交互逻辑
    6. /// </summary>
    7. public partial class MainWindow : Window
    8. {
    9. private NotifyIcon _notifyIcon = null;
    10. public MainWindow()
    11. {
    12. InitializeComponent();
    13. InitialTray(); //一启动就最小化至托盘
    14. }
    15. #region 最小化系统托盘
    16. private void InitialTray()
    17. {
    18. //隐藏主窗体
    19. this.Visibility = Visibility.Hidden;
    20. //设置托盘的各个属性
    21. _notifyIcon = new NotifyIcon();
    22. _notifyIcon.BalloonTipText = "运行中...";//托盘气泡显示内容
    23. _notifyIcon.Text = "复制助手";
    24. _notifyIcon.Visible = true;//托盘按钮是否可见
    25. _notifyIcon.Icon = new Icon(@"logo.ico");//托盘中显示的图标
    26. _notifyIcon.ShowBalloonTip(2000);//托盘气泡显示时间
    27. _notifyIcon.MouseDoubleClick += notifyIcon_MouseDoubleClick;
    28. //窗体状态改变时触发
    29. this.StateChanged += MainWindow_StateChanged;
    30. }
    31. #endregion
    32. #region 窗口状态改变
    33. private void MainWindow_StateChanged(object sender, EventArgs e)
    34. {
    35. if (this.WindowState == WindowState.Minimized)
    36. {
    37. this.Visibility = Visibility.Hidden;
    38. }
    39. }
    40. #endregion
    41. #region 托盘图标鼠标单击事件
    42. private void notifyIcon_MouseDoubleClick(object sender, System.Windows.Forms.MouseEventArgs e)
    43. {
    44. if (e.Button == MouseButtons.Left)
    45. {
    46. if (this.Visibility == Visibility.Visible)
    47. {
    48. this.Visibility = Visibility.Hidden;
    49. }
    50. else
    51. {
    52. this.Visibility = Visibility.Visible;
    53. this.Activate();
    54. }
    55. }
    56. }
    57. #endregion
    58. }
    59. }
    60. //将图标替换成下面内容,意思就是读取程序图标,来作为托盘图标
    61. //this.notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);