Using C# and WPF under .NET (rather than Windows Forms or console), what is the correct way to create an application that can only be run as a single instance?
I know it has something to do with some mythical thing called a mutex, rarely can I find someone that bothers to stop and explain what one of these are.
The code needs to also inform the already-running instance that the user tried to start a second one, and maybe also pass any command-line arguments if any existed.
It looks like there is a really good way to handle this:
WPF Single Instance Application
This provides a class you can add that manages all the mutex and messaging cruff to simplify the your implementation to the point where it's simply trivial.
I cant't find a short solution here soooo I hope someone will like this:
(Btw. put the code in you're "Program.cs")
// Optional code. If you don't want that someone runs you're ".exe" with a diffrent name:
Normally, this is the code I use for single-instance Windows Forms applications:
Where native components are:
MSDN actually has a sample application for both C# and VB to do exactly this: http://msdn.microsoft.com/en-us/library/ms771662(v=VS.90).aspx
'Another instance of the app is running. Bye'
then they're not gonna be a very happy user. You simply MUST (in a GUI application) switch to that application and pass in the arguments provided - or if command line parameters have no meaning then you must pop up the application which may have been minimized.The framework already has support for this - its just that some idiot named the DLL
Microsoft.VisualBasic
and it didn't get put intoMicrosoft.ApplicationUtils
or something like that. Get over it - or open up Reflector.Tip: If you use this approach exactly as is, and you already have an App.xaml with resources etc. you'll want to take a look at this too.
Use mutex solution:
From here.
A common use for a cross-process Mutex is to ensure that only instance of a program can run at a time. Here's how it's done:
A good feature of Mutex is that if the application terminates without ReleaseMutex first being called, the CLR will release the Mutex automatically.