As the title state, I want to make a single instance program and show MainWindow when another instance is launched. I have acheived showing message that only one instance is allowed.
public class MyApplication
{
static Mutex mutex = new Mutex(true, "FirstInstance");
[STAThread]
public static void Main(string[] args)
{
if (mutex.WaitOne(TimeSpan.Zero, true))
{
App app = new App();
app.InitializeComponent();
app.Run();
}
else
{
MessageBox.Show("only one instance at a time");
}
}
}
This works fine but I want to show MainWindow rather than a message, so I tried with
static Application app;//change app to static
if (mutex.WaitOne(TimeSpan.Zero, true))
{
app = new App();
app.InitializeComponent();
app.Run();
}
else
{
app.MainWindow.WindowState = WindowState.Normal;
}
I get "System.NullReferenceException: Object reference not set to an instance of an object". It seems MainWindow in app(which is static) is null which I don't get why.
So I tried this article http://sanity-free.org/143/csharp_dotnet_single_instance_application.html But WndProc method doesn't exist in WPF.
I'd appreciate if you can help me. Thanks!