csharp关闭窗口进入托盘
时间: 2023-05-29 12:02:50 浏览: 54
以下是C#代码,可以在关闭窗口时将应用程序转移到系统托盘中:
```csharp
//导入系统托盘的命名空间
using System.Windows.Forms;
//关闭窗口时,将应用程序转移到系统托盘
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Hide();
notifyIcon1.Visible = true;
}
//单击系统托盘的图标,恢复应用程序窗口
private void notifyIcon1_Click(object sender, EventArgs e)
{
this.Show();
notifyIcon1.Visible = false;
}
```
在窗口的FormClosing事件中,首先设置e.Cancel为true,这样就可以防止应用程序关闭窗口。然后通过this.Hide()方法来隐藏应用程序窗口,并将系统托盘的notifyIcon1.Visible属性设置为true,使其显示在屏幕上。
在系统托盘的Click事件中,使用this.Show()方法来显示应用程序窗口,并将notifyIcon1.Visible设置为false,使其从系统托盘中移除。这样就可以恢复应用程序窗口。
请注意,必须将系统托盘控件(NotifyIcon)添加到应用程序中。在窗口的Load事件中,可以添加以下代码来创建和设置NotifyIcon控件:
```csharp
private void Form1_Load(object sender, EventArgs e)
{
notifyIcon1 = new NotifyIcon();
notifyIcon1.Icon = new Icon("yourIconFilePath.ico");
notifyIcon1.Text = "Your Application Name";
}
```
在这里,我们创建了NotifyIcon控件,并通过Icon属性将其设置为应用程序图标的文件路径。Text属性用于设置当用户将鼠标指针悬停在系统托盘图标上时显示的文本。
这样就可以关闭窗口并将应用程序转移到系统托盘中。