寫過一個程序,要求在程序啟動的時候主窗口隱藏,只在系統托盤里顯示一個圖標。一直以來采用的方法都是設置窗口的showintaskbar=false, windowstate=minimized。但是偶然發現盡管這樣的方法可以使主窗口隱藏不見,但是在用alt+tab的時候卻可以看見這個程序的圖標并把這個窗口顯示出來。因此這種方法其實并不能滿足要求。
經過研究,又找到兩個方法。
方法一: 重寫setvisiblecore方法
protected override void setvisiblecore(bool value)
{
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();
}
如果需要的組件太多,這個方法就很繁瑣,因此只是做為一種可行性研究。
方法三:前面兩種方法都有一個問題,主窗口不能再顯示出來。現在這種方法就沒有這個問題了
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();
}
}
新聞熱點
疑難解答