WinForm窗口最小化到系统托盘

1. 在Form上加notifyicon控件notifyIcon1,为控件的属性Icon添加一个icon图标, Text为鼠标在图标上时显示的tip。

2. 在Form1_SizeChanged中设置Form的ShowInTaskbar属性

3. 在notifyIcon1_Click事件中设置Form的ShowInTaskbar和WindowState属性

4. 添加ContextMenuStrip控件ContextMenuStrip1,右键托盘图标弹出菜单,设置notifyIcon1的ContextMenuStrip属性为ContextMenuStrip1。在ContextMenuStrip1中添加item(退出)。

5. notifyIcon1在MouseClick事件中,判断右键点击 并弹出ContextMenuStrip。

代码:

 1     public partial class Form1 : Form
2 {
3 public Form1()
4 {
5 InitializeComponent();
6 }
7
8 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
9 {
10 this.WindowState = FormWindowState.Minimized;
11 e.Cancel = true;
12 }
13
14 private void Form1_SizeChanged(object sender, EventArgs e)
15 {
16 if (this.WindowState == FormWindowState.Minimized)
17 {
18 this.ShowInTaskbar = false;
19 }
20 }
21
22 private void notifyIcon1_Click(object sender, EventArgs e)
23 {
24 this.ShowInTaskbar = true;
25 this.WindowState = FormWindowState.Normal;
26 }
27
28 private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
29 {
30 Application.Exit();
31 }
32
33 private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
34 {
35 if (e.Button == System.Windows.Forms.MouseButtons.Right)
36 {
37 this.contextMenuStrip1.Show();
38 }
39 }
40 }

你可能感兴趣的:(WinForm)