Visaul C#托盤程序制作心得
2024-07-21 02:18:30
供稿:網友
首先,當然要引入notifyicon控件。
private system.windows.forms.notifyicon notifyiconserver;
this.notifyiconserver = new system.windows.forms.notifyicon(this.components);
接下來設置控件的各項屬性:
//
// notifyiconserver
//
this.notifyiconserver.contextmenu = this.contextmenutray;//指定上下文菜單
this.notifyiconserver.icon = ((system.drawing.icon)(resources.getobject("notifyiconserver.icon")));//指定圖標
this.notifyiconserver.text = "my server";//指定鼠標懸停顯示
this.notifyiconserver.mousedown += new system.windows.forms.mouseeventhandler(this.notifyiconserver_mousedown);
this.notifyiconserver.doubleclick += new system.eventhandler(this.notifyiconserver_doubleclick);
//
// contextmenutray 上下文菜單
//
this.contextmenutray.menuitems.addrange(new system.windows.forms.menuitem[] {
this.menuitem1,
this.menuitem2});
//
// menuitem1
//
this.menuitem1.index = 0;
this.menuitem1.text = "打開 chat server";
this.menuitem1.click += new system.eventhandler(this.menuitem1_click);
//
// menuitem2
//
this.menuitem2.index = 1;
this.menuitem2.text = "退出程序";
this.menuitem2.click += new system.eventhandler(this.menuitem2_click);
用戶點擊窗體的“關閉”小按鈕時,并不真正關閉窗體,而是將程序放到系統托盤。
private void chatform_closing(object sender, system.componentmodel.canceleventargs e)
{
e.cancel = true; // 取消關閉窗體
this.hide();
this.showintaskbar = false;
this.notifyiconserver.visible = true;//顯示托盤圖標
}
notifyicon的雙擊事件,可以恢復程序窗體:
private void notifyiconserver_doubleclick(object sender, system.eventargs e)
{
this.show();
if (this.windowstate == formwindowstate.minimized)
this.windowstate = formwindowstate.normal;
this.activate();
}
附加要求:單擊鼠標左鍵也可調出一菜單。
解決方案如下:
首先聲明一個上下文菜單:
//
// contextmenuleft 左鍵菜單
//
this.contextmenuleft.menuitems.addrange(new system.windows.forms.menuitem[] {
this.menuitem3});
//
// menuitem3
//
this.menuitem3.index = 0;
this.menuitem3.text = "關于……";
由于不能在notifyicon上直接顯示上下文菜單,只有創建一個control作為容器,這是權宜之計,應該有更好的方法吧。
private void notifyiconserver_mousedown(object sender, system.windows.forms.mouseeventargs e)
{
if(e.button==mousebuttons.left)
{
control control = new control(null,control.mouseposition.x,control.mouseposition.y,1,1);
control.visible = true;
control.createcontrol();
point pos = new point(0,0);//這里的兩個數字要根據你的上下文菜單大小適當地調整
this.contextmenuleft.show(control,pos);
}
}