Click here to Skip to main content
Click here to Skip to main content

WPF Single Instance Application

By , 28 May 2010
 

The Problem

The question this post solves is how to enforce that your WPF application has only one instance?

Solution Source

The solution is based on code found in some WPF reference applications which Microsoft will soon (?) release. I didn't write it, but I used it several times and it’s the best solution I've found to date, so I'd hate to see it unpublished.

Solution Advantages

So, what are the advantages of this solution? After all, it’s not the first time someone posts a solution for this problem.

Well, the most important advantage is that it works.
No glitches. No special cases. No inherent race conditions.
It simply works.

Second, it’s easily used. In the next section, I'll show you exactly how to use it.

Third, there are no constraints on your WPF application. Specifically, your main application / window class doesn't have to inherit some base class for this to work.

And at last, you don't need to be dependent on any VB DLL.
I say this because one of the popular solutions for this problem requires you to add a reference to a (WinForms related!) Visual Basic DLL, which may feel strange for some people.

As a bonus, the solution provides to the first instance the parameters of the second instance when run. This is very useful if you want to integrate you application with the Windows 7 taskbar.

Solution Details

So, let’s see how to make your WPF application having just one instance.

Step 1: Add the file SingleInstance.cs to your project.

Step 2: Add a reference to your project: System.Runtime.Remoting.

Step 3: Have your application class implement ISingleInstanceApp (defined in SingleInstance.cs).

The only method in this interface is:

bool SignalExternalCommandLineArgs(IList<string> args)

This method is called when a second instance of your application tries to run. It has an args parameter which is the same as the command line arguments passed to the second instance.

Step 4: Define your own Main function that uses the single instance class.

Your App class should now be similar to this:

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application, ISingleInstanceApp
{
    private const string Unique = "My_Unique_Application_String";
    [STAThread]
    public static void Main()
    {
        if (SingleInstance<App>.InitializeAsFirstInstance(Unique))
        {
            var application = new App();
            application.InitializeComponent();
            application.Run();
            // Allow single instance code to perform cleanup operations
            SingleInstance<App>.Cleanup();
        }
    }
    #region ISingleInstanceApp Members
    public bool SignalExternalCommandLineArgs(IList<string> args)
    {
        // handle command line arguments of second instance
        // ...
        return true;
    }
    #endregion
}

Step 5: Set new main entry point.

Select Project Properties –> Application and set “Startup object” to your App class name instead of “(Not Set)”.

Step 6: Cancel the default WPF main function.

Right click on App.xaml, Properties, set Build Action to "Page" instead of "Application Definition".

Solution Inner Works

I can summarize it as: Mutex and Remoting, done right.
If you want to know more details, just have a look at the code.

You can find a WPF sample application here.

That’s it for now,
Arik Poznanski.

kick it on DotNetKicks.com Shout it

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)

About the Author

Arik Poznanski
Software Developer (Senior) Sela Technology Center
Israel Israel
Member
Arik Poznanski is a Senior Consultant and Instructor at Sela Technology Center. He completed two B.Sc. degrees in Mathematics & Computer Science, summa cum laude, from the Technion in Israel.
 
Arik has extensive knowledge and experience in many Microsoft technologies, including .NET with C#, WPF, Silverlight, WinForms, Interop, COM/ATL programming, C++ Win32 programming and reverse engineering (assembly, IL).

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionHow to bring the window into view?memberChristoph19729 Mar '13 - 7:36 
AnswerRe: How to bring the window into view?memberMember 787310314 Mar '13 - 22:50 
AnswerThis saved my daymemberSascha Nitschke4 Nov '12 - 4:23 
GeneralMy vote of 5memberAnand Murali M S19 Sep '12 - 19:48 
QuestionGreat article, but - how do we prevent the loss of inheritance of the App.xaml resources? [modified]memberJamesWittHurst12 Aug '12 - 22:01 
AnswerRe: Great article, but - how do we prevent the loss of inheritance of the App.xaml resources?memberN Jones24 Sep '12 - 3:33 
GeneralRe: Great article, but - how do we prevent the loss of inheritance of the App.xaml resources?memberJamesWittHurst24 Jan '13 - 8:29 
GeneralMy vote of 5memberMartin Mikula VSBTU17 Jul '12 - 4:15 
GeneralMy vote of 5memberJennie MG22 Jun '12 - 8:47 
GeneralMy vote of 5memberMember 867463424 Mar '12 - 10:36 
GeneralMy vote of 4memberNinjaCross17 Feb '12 - 0:46 
QuestionHelp neededmemberMember 858049130 Jan '12 - 23:03 
QuestionMy vote of 5, however doesn't work on Terminal Servicesmemberp.moretti29 Jan '12 - 22:12 
GeneralMy vote of 5memberEbrahimAsadi8 Jul '11 - 21:47 
GeneralMy vote of 5memberGuilherme Meinlschmiedt Abdo19 May '11 - 3:49 
GeneralMy vote of 5membervenumadhavv21 Mar '11 - 3:11 
GeneralFantastic, one question remainingmemberxtremecj15 Feb '11 - 3:44 
GeneralGreat solutionmembertomlev17 Jul '10 - 14:06 
GeneralGood workmemberLeung Yat Chun28 May '10 - 6:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 28 May 2010
Article Copyright 2010 by Arik Poznanski
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid