1. 程式人生 > >WinForm中 最小化到托盤

WinForm中 最小化到托盤

1.設定WinForm窗體屬性showinTask=false 
2.加notifyicon控制元件notifyIcon1,為控制元件notifyIcon1的屬性Icon新增一個icon圖示。 
3.新增窗體最小化事件(首先需要新增事件引用): 
程式碼如下:
this.SizeChanged += new System.EventHandler(this.Form1_SizeChanged); 
//上面一行是主窗體InitializeComponent()方法中需要新增的引用 
private void Form1_SizeChanged(object sender, EventArgs e) 
{ 
if(this.WindowState == FormWindowState.Minimized) 
{ 
this.Hide(); 
this.notifyIcon1.Visible=true; 
} 
} 

4.新增點選圖示事件(首先需要新增事件引用): 
private void notifyIcon1_Click(object sender, EventArgs e) 
{ 
this.Visible = true; 
this.WindowState = FormWindowState.Normal; 
this.notifyIcon1.Visible = false; 
} 
5.可以給notifyIcon新增右鍵選單: 
主窗體中拖入一個ContextMenu控制元件NicontextMenu,點中控制元件,在上下文選單中新增選單,notifyIcon1的ContextMenu行為中選中NicontextMenu 作為上下文選單。 
程式碼如下: 
protected override void OnClosing(CancelEventArgs e) 
{ 
this.ShowInTaskbar = false; 
this.WindowState = FormWindowState.Minimized; 
e.Cancel = true; 
} 
protected override void OnClosing(CancelEventArgs e) 
{ 
//this.ShowInTaskbar = false; 
this.WindowState = FormWindowState.Minimized; 
e.Cancel = true; 
} 
private void CloseCtiServer() 
{ 
timer.Enabled = false; 
DJ160API.DisableCard(); 
this.NotifyIcon.Visible = false; 
this.Close(); 
this.Dispose(); 
Application.Exit(); 
} 
private void HideCtiServer() 
{ 
this.Hide(); 
} 
private void ShowCtiServer() 
{ 
this.Show(); 
this.WindowState = FormWindowState.Normal; 
this.Activate(); 
} 
private void CtiManiForm_Closing(object sender, System.ComponentModel.CancelEventArgs e) 
{ 
this.CloseCtiServer(); 
} 
private void menuItem_Show_Click(object sender, System.EventArgs e) 
{ 
this.ShowCtiServer(); 
}  
private void menuItem_Exit_Click(object sender, System.EventArgs e) 
{ 
this.CloseCtiServer(); 
} 
private void menuItem_Hide_Click(object sender, System.EventArgs e) 
{ 
this.HideCtiServer(); 
} 
private void CtiManiForm_SizeChanged(object sender, System.EventArgs e) 
{ 
if(this.WindowState == FormWindowState.Minimized) 
{ 
this.HideCtiServer(); 
} 
} 
private void notifyIcon1_DoubleClick(object sender,System.EventArgs e) 
{ 
this.ShowCtiServer(); 
}