× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Check if other instances of a WPF application are/aren't running

Gayot Fow
Feb 05, 2015
<p>The get processes by name strategy can fail if the exe has been copied and renamed. Debugging can also be problematic because .vshost is appended to the process name.</p> <p>To create a single instance application in WPF, you can start by removing the StartupUri attribute from the App.Xaml file so that it looks like this...</p> <pre><code>&lt;Application x:Class="SingleInstance.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;/Application&gt; </code></pre> <p>After that, you can go to the App.xaml.cs file and change it so it looks like this...</p> <pre><code>public partial class App { // give the mutex a unique name private const string MutexName = "##||ThisApp||##"; // declare the mutex private readonly Mutex _mutex; // overload the constructor bool createdNew; public App() { // overloaded mutex constructor which outs a boolean // telling if the mutex is new or not. // see http://msdn.microsoft.com/en-us/library/System.Threading.Mutex.aspx _mutex = new Mutex(true, MutexName, out createdNew); if (!createdNew) { // if the mutex already exists, notify and quit MessageBox.Show("This program is already running"); Application.Current.Shutdown(0); } } protected override void OnStartup(StartupEventArgs e) { if (!createdNew) return; // overload the OnStartup so that the main window // is constructed and visible MainWindow mw = new MainWindow(); mw.Show(); } } </code></pre> <p>This will test if the mutex exists and if it does exist, the app will display a message and quit. Otherwise the application will be constructed and the OnStartup override will be called.</p> <p>Depending upon your version of Windows, raising the message box will also push the existing instance to the top of the Z order. If not you can ask another question about bringing a window to the top.</p> <p>There are additional features in the Win32Api that will help further customize the behaviour.</p> <p>This approach gives you the message notification you were after and assures that only one instance of the main window is ever created.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/18270167/Check%20if%20other%20instances%20of%20a%20WPF%20application%20are/aren't%20running/18272993">Stack Overflow</a>.</p>
comments powered by Disqus