C# 最小化到系统托盘的实现(一)
最近做个小程序试验, 没有时间一直研究,偷偷用了些上班时间完成了.
目标:程序点击关闭后,弹出一个对话框,选择退出,最小化,或者取消.然后系统托盘双击,可以打开最小化的程序,右键有菜单,菜单里有个"选项",可以设置每次点击关闭按钮时是否弹出这个对话框.
难点:增加一个"下次不再提示"的comboBox到对话框中.
使用到的知识:
1. 非模态对话框: CloseDialog.Show();
模态对话框: CloseDialog.ShowDialog();
2. 禁止拉伸对话框: this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
3. 最小化到托盘的实现:
3.1.加notifyicon控件notifyIcon,为控件notifyIcon的属性Icon添加一个icon图标
3.2.添加事件:
private void QPan_SizeChanged(object sender, System.EventArgs e)
{
if(this.WindowState == System.Windows.Forms.FormWindowState.Minimized)
{
this.QPan_MiniMizedToTuoPan();
}
}
//最小化到托盘,函数
public void QPan_MiniMizedToTuoPan()
{
this.Hide();
this.ShowInTaskbar = false;
this.notifyIcon.Visible = true;
}
4.托盘双击:
//双击托盘图标
private void notifyIcon_DoubleClick(object sender, System.EventArgs e)
{
this.QPan_OpenFromTuoPan();
}
//从托盘返回,函数
Public void QPan_OpenFromTuoPan()
{
this.Visible = true;
this.Show();
this.ShowInTaskbar = true;
this.WindowState = System.Windows.Forms.FormWindowState.Normal;
this.notifyIcon.Visible = true;
}
5.右键菜单:
5.1.增加一个ContextmenuStrip
5.2.增加菜单项:
// TuoPanContextMenuStrip
//
this.TuoPanContextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.TrayOptions,
this.TraySeparator1,
this.TrayOpen,
this.TrayExit});
this.TuoPanContextMenuStrip.Name = "TuoPancontextMenuStrip";
this.TuoPanContextMenuStrip.Size = new System.Drawing.Size(112, 76);
//
// TrayOptions
//
this.TrayOptions.Name = "TrayOptions";
this.TrayOptions.Size = new System.Drawing.Size(111, 22);
this.TrayOptions.Text = "Options";
this.TrayOptions.Click += new System.EventHandler(this.OpenSettingOptions);
//
// TraySeparator1
//
this.TraySeparator1.Name = "TraySeparator1";
this.TraySeparator1.Size = new System.Drawing.Size(108, 6);
//
// TrayOpen
//
this.TrayOpen.Name = "TrayOpen";
this.TrayOpen.Size = new System.Drawing.Size(111, 22);
this.TrayOpen.Text = "Open";
this.TrayOpen.Click += new System.EventHandler(this.OpenQPan);
//
// TrayExit
//
this.TrayExit.Name = "TrayExit";
this.TrayExit.Size = new System.Drawing.Size(111, 22);
this.TrayExit.Text = "Exit";
this.TrayExit.Click += new System.EventHandler(this.CloseQPan);
//
5.3.给菜单项增加事件:
//退出
private void CloseQPan(object sender, System.EventArgs e)
{
boolCloseFromExitMenu = true;
Application.Exit();
}
//打开
private void OpenQPan(object sender, System.EventArgs e)
{
this.QPan_OpenFromTuoPan();
}
//打开选项设置
private void OpenSettingOptions(object sender, System.EventArgs e)
{
this.NewOptionDialog.ShowDialog();
}