方法一: 重写setVisibleCore方法
protected
override
void SetVisibleCore(
bool value)
{
base.SetVisibleCore( false);
}
{
base.SetVisibleCore( false);
}
这个方法比较简单,但是使用了这个方法后主窗口就再也不能被显示出来,而且在退出程序的时候也必须调用Application.Exit方法而不是Close方法。这样的话就要考虑一下,要把主窗口的很多功能放到其他的地方去。
方法二: 不创建主窗口,直接创建NotifyIcon和ContextMenu组件
这种方法比较麻烦,很多代码都必须手工写
static
void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault( false);
System.Resources.ResourceManager resources =
new System.Resources.ResourceManager("myResource", System.Reflection.Assembly.GetExecutingAssembly());
NotifyIcon ni = new NotifyIcon();
ni.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Warning;
ni.BalloonTipText = "test!";
ni.BalloonTipTitle = "test.";
// ni.ContextMenuStrip = contextMenu;
ni.Icon = ((System.Drawing.Icon)(resources.GetObject("ni.Icon")));
ni.Text = "Test";
ni.Visible = true;
ni.MouseClick += delegate( object sender, MouseEventArgs e)
{
ni.ShowBalloonTip(0);
};
Application.Run();
}
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault( false);
System.Resources.ResourceManager resources =
new System.Resources.ResourceManager("myResource", System.Reflection.Assembly.GetExecutingAssembly());
NotifyIcon ni = new NotifyIcon();
ni.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Warning;
ni.BalloonTipText = "test!";
ni.BalloonTipTitle = "test.";
// ni.ContextMenuStrip = contextMenu;
ni.Icon = ((System.Drawing.Icon)(resources.GetObject("ni.Icon")));
ni.Text = "Test";
ni.Visible = true;
ni.MouseClick += delegate( object sender, MouseEventArgs e)
{
ni.ShowBalloonTip(0);
};
Application.Run();
}
如果需要的组件太多,这个方法就很繁琐,因此只是做为一种可行性研究。
方法三:前面两种方法都有一个问题,主窗口不能再显示出来。现在这种方法就没有这个问题了
private
bool windowCreate=
true;
...
protected override void OnActivated(EventArgs e)
{
if (windowCreate)
{
base.Visible = false;
windowCreate = false;
}
base.OnActivated(e);
}
private void notifyIcon1_DoubleClick( object sender, EventArgs e)
{
if ( this.Visible == true)
{
this.Hide();
this.ShowInTaskbar = false;
}
else
{
this.Visible = true;
this.ShowInTaskbar = true;
this.WindowState = FormWindowState.Normal;
// this.Show();
this.BringToFront();
}
}
...
protected override void OnActivated(EventArgs e)
{
if (windowCreate)
{
base.Visible = false;
windowCreate = false;
}
base.OnActivated(e);
}
private void notifyIcon1_DoubleClick( object sender, EventArgs e)
{
if ( this.Visible == true)
{
this.Hide();
this.ShowInTaskbar = false;
}
else
{
this.Visible = true;
this.ShowInTaskbar = true;
this.WindowState = FormWindowState.Normal;
// this.Show();
this.BringToFront();
}
}