0

I have a C#/WPF application that consists of a mainwindow and a system tray icon. I have configured App.xaml with ShutdownMode="OnExplicitShutdown" in order to keep the application running in the system tray upon closing the main window.

In the context menu of the system tray icon, I have menu items bound to methods that re-open the main Window:

private void SysTray_Information_Click(object sender, RoutedEventArgs e)
{
    var newWindow = new MainWindow();
    newWindow.Show();
    MainWindow.Focus();
}

I would like to add to these methods a check to see if the mainwindow is already being displayed (hasn't been closed). Otherwise it will be possible to open multiple copies of the mainwindow. How can I achieve this?

Mo Patel
  • 2,321
  • 4
  • 22
  • 37
user3342256
  • 1,238
  • 4
  • 21
  • 35

2 Answers2

2

A semaphore or a mutex would be appropriate at the application level. This code is for a WinForms app but I am sure it can be modified to suite your needs.

static void Main()
{
    System.Threading.Mutex appMutex = new System.Threading.Mutex(true, "MyApplicationName", out exclusive);
    if (!exclusive)
    {
        MessageBox.Show("Another instance of My Program is already running.","MyApplicationName",MessageBoxButtons.OK,MessageBoxIcon.Exclamation );
        return;
    }
    Application.Run(new frmMyAppMain());
    GC.KeepAlive(appMutex);
}
Vizel Leonid
  • 456
  • 7
  • 15
Ross Bush
  • 14,648
  • 2
  • 32
  • 55
  • Actually, I re-read your original post. This would work for your sys tray application. However, determining if the main form is active is different, sorry. – Ross Bush Apr 24 '14 at 01:43
1

It sounds like you could use a static variable for this:

public class MainWindow : Window
{
    private static bool _isInstanceDisplayed = false;
    public static bool IsInstanceDisplayed() { return _isInstanceDisplayed; }
}

Set it to true when you load the window. Then you can check as needed using:

if (MainWindow.IsInstanceDisplayed()) { ... }
McGarnagle
  • 101,349
  • 31
  • 229
  • 260