2

I have an app that minimizes to the system tray by clicking on "close" button and I want to save it's state (position, all elements (comboboxes, textboxes) with their values, etc).

Now I wrote this code, but it creates a new window from tray (instead of recovering the old one, with its parameters):

# 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();
      })

});

How I can modify this code for my problem?

Paolo Moretti
  • 54,162
  • 23
  • 101
  • 92
Roman Nazarkin
  • 2,209
  • 5
  • 23
  • 44

1 Answers1

1

When you hold a reference to your `MainWindow´ then you can simple call Show() again after closing it. Closing the Window will simply hide it and calling Show again will restore it.

private Window m_MainWindow;

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

    m_MainWindow.Show();
  };

If you´re sure that the MainWidnow is your Applications primary Window then you can also use this:

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

I would prefer the first variant since it´s explicit.

Mecaveli
  • 1,507
  • 10
  • 16
  • Ok, sounds good, but how i can save `MainWindow` instance to `m_MainWindow` var at first run of window? – Roman Nazarkin Apr 30 '13 at 13:58
  • At some point you´ll create a instance of the window won´t you? If you don´t explicitly create it, you could use the Application.MainWindow Property which gets set automatically, see http://msdn.microsoft.com/en-us/library/system.windows.application.mainwindow.aspx – Mecaveli Apr 30 '13 at 14:02
  • Yep, it worked(i used a `this.MainWindow` variable)! Thank you soo much! – Roman Nazarkin Apr 30 '13 at 14:07