`

c# 任务栏托盘代码

    博客分类:
  • c#
 
阅读更多

转载:http://www.cnblogs.com/dooroo/archive/2012/09/09/2677315.html

 

winform托盘的使用主要用到了两个控件notifyIcon和contextMenuStrip
(一)notifyIcon的使用
1)先在工具箱中拖到主窗体中,直接在属性icon中选择一个ICO图标作为托盘图标,并把主窗口的属性ShowInTaskbar是否出现在任务栏中设置为假
2)添加以下事件和语句
private void Form1_SizeChanged(object sender, EventArgs e)
{//窗口尺寸改变事件:即点最小化时(最好窗口是固定大小)
if (this.WindowState == FormWindowState.Minimized)
{
this.Hide();//隐藏主窗口
this.notifyIcon1.Visible = true;//托盘为真
}
}
//双击托盘,窗口恢复正常
private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
}
3)这里涉及到如果窗口有关闭按钮(最好是自己做关闭按钮),把关闭按钮改为最小化
protected override void WndProc(ref Message m)
{//重装API中的关闭
const int WM_SYSCOMMAND = 0x0112;
const int SC_CLOSE = 0xF060;
if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE)
{//捕捉关闭窗体消息
this.WindowState = FormWindowState.Minimized;
return;
}
base.WndProc(ref m);
}
如果是自己做的关闭按钮,直接用第2)步的方法即可.

(二)为了让托盘图标有右键菜单功能,需要添加contextMenuStrip
1)从工具箱中拖contextMenuStrip控件到主窗体
2)为contextMenuStrip设置菜单项
3)为notifyIcon属性中关联contextMenuStrip
4)假设双击托盘或托盘菜单中"显示主窗口":
//双击托盘,窗口恢复正常
private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
}
//菜单:显示主窗口
private void 主窗口_Click(object sender, EventArgs e)
{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
}
//菜单:退出功能
private void 退出_Click(object sender, EventArgs e)
{
this.Close();
}
另:如果想加一个关闭窗口时提示:确定退出?"是"则退出,"否"则最小化,并提供一个checkbox记住以后都按相同的操作,还会有一点麻烦,下次再研究.

if (MessageBox.Show("确定退出?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
{
Application.Exit();
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics