Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 118483
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T03:30:06+00:00 2026-05-11T03:30:06+00:00

Using C# and WPF under .NET (rather than Windows Forms or console), what is

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T03:30:07+00:00Added an answer on May 11, 2026 at 3:30 am

    Here is a very good article regarding the Mutex solution. The approach described by the article is advantageous for two reasons.

    First, it does not require a dependency on the Microsoft.VisualBasic assembly. If my project already had a dependency on that assembly, I would probably advocate using the approach shown in another answer. But as it is, I do not use the Microsoft.VisualBasic assembly, and I’d rather not add an unnecessary dependency to my project.

    Second, the article shows how to bring the existing instance of the application to the foreground when the user tries to start another instance. That’s a very nice touch that the other Mutex solutions described here do not address.


    UPDATE

    As of 8/1/2014, the article I linked to above is still active, but the blog hasn’t been updated in a while. That makes me worry that eventually it might disappear, and with it, the advocated solution. I’m reproducing the content of the article here for posterity. The words belong solely to the blog owner at Sanity Free Coding.

    Today I wanted to refactor some code that prohibited my application from running multiple instances of itself.

    Previously I had use System.Diagnostics.Process to search for an instance of my myapp.exe in the process list. While this works, it brings on a lot of overhead, and I wanted something cleaner.

    Knowing that I could use a mutex for this (but never having done it before) I set out to cut down my code and simplify my life.

    In the class of my application main I created a static named Mutex:

    static class Program {     static Mutex mutex = new Mutex(true, '{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}');     [STAThread]     ... } 

    Having a named mutex allows us to stack synchronization across multiple threads and processes which is just the magic I’m looking for.

    Mutex.WaitOne has an overload that specifies an amount of time for us to wait. Since we’re not actually wanting to synchronizing our code (more just check if it is currently in use) we use the overload with two parameters: Mutex.WaitOne(Timespan timeout, bool exitContext). Wait one returns true if it is able to enter, and false if it wasn’t. In this case, we don’t want to wait at all; If our mutex is being used, skip it, and move on, so we pass in TimeSpan.Zero (wait 0 milliseconds), and set the exitContext to true so we can exit the synchronization context before we try to aquire a lock on it. Using this, we wrap our Application.Run code inside something like this:

    static class Program {     static Mutex mutex = new Mutex(true, '{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}');     [STAThread]     static void Main() {         if(mutex.WaitOne(TimeSpan.Zero, true)) {             Application.EnableVisualStyles();             Application.SetCompatibleTextRenderingDefault(false);             Application.Run(new Form1());             mutex.ReleaseMutex();         } else {             MessageBox.Show('only one instance at a time');         }     } } 

    So, if our app is running, WaitOne will return false, and we’ll get a message box.

    Instead of showing a message box, I opted to utilize a little Win32 to notify my running instance that someone forgot that it was already running (by bringing itself to the top of all the other windows). To achieve this I used PostMessage to broadcast a custom message to every window (the custom message was registered with RegisterWindowMessage by my running application, which means only my application knows what it is) then my second instance exits. The running application instance would receive that notification and process it. In order to do that, I overrode WndProc in my main form and listened for my custom notification. When I received that notification I set the form’s TopMost property to true to bring it up on top.

    Here is what I ended up with:

    • Program.cs
    static class Program {     static Mutex mutex = new Mutex(true, '{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}');     [STAThread]     static void Main() {         if(mutex.WaitOne(TimeSpan.Zero, true)) {             Application.EnableVisualStyles();             Application.SetCompatibleTextRenderingDefault(false);             Application.Run(new Form1());             mutex.ReleaseMutex();         } else {             // send our Win32 message to make the currently running instance             // jump on top of all the other windows             NativeMethods.PostMessage(                 (IntPtr)NativeMethods.HWND_BROADCAST,                 NativeMethods.WM_SHOWME,                 IntPtr.Zero,                 IntPtr.Zero);         }     } } 
    • NativeMethods.cs
    // this class just wraps some Win32 stuff that we're going to use internal class NativeMethods {     public const int HWND_BROADCAST = 0xffff;     public static readonly int WM_SHOWME = RegisterWindowMessage('WM_SHOWME');     [DllImport('user32')]     public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam);     [DllImport('user32')]     public static extern int RegisterWindowMessage(string message); } 
    • Form1.cs (front side partial)
    public partial class Form1 : Form {     public Form1()     {         InitializeComponent();     }     protected override void WndProc(ref Message m)     {         if(m.Msg == NativeMethods.WM_SHOWME) {             ShowMe();         }         base.WndProc(ref m);     }     private void ShowMe()     {         if(WindowState == FormWindowState.Minimized) {             WindowState = FormWindowState.Normal;         }         // get our current 'TopMost' value (ours will always be false though)         bool top = TopMost;         // make our form jump to the top of everything         TopMost = true;         // set it back to whatever it was         TopMost = top;     } } 
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 74k
  • Answers 74k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • added an answer You do not have to specify a Path if you… May 11, 2026 at 2:27 pm
  • added an answer I had the exact same error! I even opened a… May 11, 2026 at 2:27 pm
  • added an answer Try: $('#myarea')[0].selectionStart; Why? A jQuery selector does not return the… May 11, 2026 at 2:27 pm

Related Questions

fellow anthropoids and lily pads and paddlewheels! I'm developing a Windows desktop app in
There are two projects in one VS solution: client(wpf app) and а wcf service
If I were to want to create a nice looking widget to stay running
Just for kicks I'm playing around a bit with C# and WPF. I'm going

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.