How can I create a single-instance application using WPF?

Mutex : Mutual Exclusion, single-instance behavior

The classic approach to implementing single-instance behavior still applies to WPF
applications: Use a named (and, therefore, operating system-wide) mutex. The following code shows how you can do this in C#:

bool mutexIsNew; 
using (System.Threading.Mutex m = 
new System.Threading.Mutex(true, uniqueName, out mutexIsNew)) 
{
if (mutexIsNew) 
// This is the first instance. Run the application.
else 
// There is already an instance running. Exit!
}

Just be sure that uniqueName won’t be chosen by other applications! It’s common to generate a globally unique identifier (GUID) at development time and use that as your identifier. Of course, nothing prevents a malicious application from creating a semaphore with the same name to prevent such an application from running!

It is often desirable to communicate the command-line arguments to the running instance rather than silently exiting the duplicate instance. The only functionality in the .NET Framework for this is provided by the Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase class
which, despite its name, is usable from any .NET language and with WPF. Alternatively, the first instance could open an RPC channel and then any new instances can try to connect to it in order to communicate this information.



댓글

이 블로그의 인기 게시물

Oracle NLS_DATE_FORMAT 변경

Stop console process using Ctrl+C.

Alternative to IValueConvert, QuickConverter