使用 WPF 最小化/关闭系统托盘的应用程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27265139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Minimizing/Closing Application to system tray using WPF
提问by Fahad
I want to add application in System Tray when user minimize or close the form. I have done it for the Minimize case. Can anyone tell me that how i can keep my app running and add it into System Tray when I close the form?
当用户最小化或关闭表单时,我想在系统托盘中添加应用程序。我已经为最小化案例做了它。谁能告诉我如何在关闭表单时保持我的应用程序运行并将其添加到系统托盘中?
public MainWindow()
{
InitializeComponent();
System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();
ni.Icon = new System.Drawing.Icon(Helper.GetImagePath("appIcon.ico"));
ni.Visible = true;
ni.DoubleClick +=
delegate(object sender, EventArgs args)
{
this.Show();
this.WindowState = System.Windows.WindowState.Normal;
};
SetTheme();
}
protected override void OnStateChanged(EventArgs e)
{
if (WindowState == System.Windows.WindowState.Minimized)
this.Hide();
base.OnStateChanged(e);
}
回答by TheMiddleMan
You can also override OnClosingto keep the app running and minimize it to the system tray when a user closes the application.
您还可以覆盖OnClosing以保持应用程序运行并在用户关闭应用程序时将其最小化到系统托盘。
MainWindow.xaml.cs
主窗口.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
// Minimize to system tray when application is minimized.
protected override void OnStateChanged(EventArgs e)
{
if (WindowState == WindowState.Minimized) this.Hide();
base.OnStateChanged(e);
}
// Minimize to system tray when application is closed.
protected override void OnClosing(CancelEventArgs e)
{
// setting cancel to true will cancel the close request
// so the application is not closed
e.Cancel = true;
this.Hide();
base.OnClosing(e);
}
}
回答by Pavel Ivchenkov
You need not use OnStateChanged(). Instead, use the PreviewClosedevent.
您不需要使用OnStateChanged(). 相反,使用PreviewClosed事件。
public MainWindow()
{
...
PreviewClosed += OnPreviewClosed;
}
private void OnPreviewClosed(object sender, WindowPreviewClosedEventArgs e)
{
m_savedState = WindowState;
Hide();
e.Cancel = true;
}

