Visaul C#托盘程序制作心得

来源:互联网 发布:雪梨淘宝店铺叫什么 编辑:程序博客网 时间:2024/06/02 02:45

首先,當然要引入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);
}
}



原创粉丝点击