当应用程序在托盘中保存窗口状态

本文关键字:保存 窗口 状态 应用程序 | 更新日期: 2023-09-27 18:11:43

我有一个应用程序,通过点击"关闭"按钮最小化到系统托盘,我想保存它的状态(位置,所有元素(组合框,文本框)及其值等)。

现在我写了这段代码,但是它从托盘中创建了一个新窗口(而不是恢复旧的窗口和它的参数):

# app.xaml.cs:
this.ShutdownMode = ShutdownMode.OnExplicitShutdown;
// create a system tray icon
var ni = new System.Windows.Forms.NotifyIcon();
ni.Visible = true;
ni.Icon = QuickTranslator.Properties.Resources.MainIcon;
ni.DoubleClick +=
  delegate(object sender, EventArgs args)
  {
    var wnd = new MainWindow();
    wnd.Visibility = Visibility.Visible;
  };
// set the context menu
ni.ContextMenu = new System.Windows.Forms.ContextMenu(new[]
{
    new System.Windows.Forms.MenuItem("About", delegate
    {
      var uri = new Uri("AboutWindow.xaml", UriKind.Relative);
      var wnd = Application.LoadComponent(uri) as Window;
      wnd.Visibility = Visibility.Visible;
    }),
    new System.Windows.Forms.MenuItem("Exit", delegate
      {
        ni.Visible = false;
        this.Shutdown();
      })
});

我如何修改这段代码来解决我的问题?

当应用程序在托盘中保存窗口状态

当你持有一个对' MainWindow '的引用时,你可以在关闭它后再次调用Show()。关闭窗口只会隐藏它,再次调用Show将恢复它。

private Window m_MainWindow;
ni.DoubleClick +=
  delegate(object sender, EventArgs args)
  {
    if(m_MainWindow == null)
        m_MainWindow = new MainWindow();
    m_MainWindow.Show();
  };

如果你确定MainWidnow是你的应用程序主窗口,那么你也可以使用这个:

ni.DoubleClick +=
  delegate(object sender, EventArgs args)
  {
    Application.MainWindow.Show();
  };

我更喜欢第一个变体,因为它是显式的。