//本文转载自百度文库
拉一个NotifyIcon控件notifyIcon1,为控件notifyIcon1的属性Icon添加一个icon图标。
添加一个ContextMenuStrip控件,然后设置notifyIcon1的属性ContextMenuStrip为你添加的contextMenuStrip1
如果不想让程序在任务栏中显示,请把窗体的属性ShowInTaskbar设置为false
代码:
//最小化事件,显示到托盘
private void Form1_Resize(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.Visible = false;
}
}
//托盘图标单击显示
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
this.Visible = true;
this.TopMost = true;
this.WindowState = FormWindowState.Normal;
this.Activate();
}
//假关闭,关闭时隐藏
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Visible = false;
}
网上好多文章讲的开机自启动并最小化托盘好多都是假的,并没有实现开机启动的时候最小化
经过今天一番研究,经验分享:
//加入注册表启动项
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
if (key == null)
{
key = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
key.SetValue("xxx系统", this.GetType().Assembly.Location + " -s");
}
else
{
key.SetValue("xxx系统", this.GetType().Assembly.Location + " -s");
}
key.Close();
然后在program.cs中
然后Form1的load事件中判断 args,如果正常双击打开的话,是没有命令参数的,也就是args为空,此时让Form1显示,
如果是注册表开机启动的话,则args的值不为空,为命令行参数-s,此时应让Form1隐藏
代码如下:
String arg = null;
public Form1(String[] args)
{
if (args.Length > 0)
{
//获取启动时的命令行参数
arg = args[0];
}
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
if (arg != null)
{
//arg不为空,说明有启动参数,是从注册表启动的,则直接最小化到托盘
this.Visible = false;
this.ShowInTaskbar = false;
}
}
设置注册表启动时多加一项 命令行 -s(注:这个内容由你自定义,-a -b -abc 都行)