Reputation: 1290
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?
Upvotes: 0
Views: 784
Reputation: 15155
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);
}
Upvotes: 2
Reputation: 102723
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()) { ... }
Upvotes: 1