Discussing the nuts and bolts of software development

Monday, March 09, 2009

 

Single Instance Applications in WPF

In some design scenarios launching multiple copies of the same WPF application is a problem, especially for document-based applications or server applications.

WPF does not provide a native solution for single instance applications; however there are several workarounds for this issue.

The most commonly used solution is to check whether another instance of the application is already running when the Application.Startup event fires. This is easily done using a system wide mutex (provided by the operating system to allow interprocess communication). While this is easily done, it limits the developer’s options by not providing a way for the new instance to communicate with the already running instance. Mainly this will provide only a simple way of limiting the number of running instances to one, while a separate system will be required to handle the new calls (usually through remoting or Windows Communication Foundation).

The recommended and more useful approach is to use the built-in support that’s provided in Windows Forms and originally intended for Visual Basic applications. This approach handles the messy plumbing behind the scenes. This means using an old style application class as wrapper for the WPF application. The wrapper will handle the instance management and will communicate the request to the already running instance of the WPF application.

Solution steps:

1) Add a reference to the Microsoft.VisualBasic.dll assembly.

2) Add a new custom class derived from the Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase class.

3) The IsSingleInstance must be set to true in the constructor. This enables a single instance application.

4) Override the OnStartup() method to create the WPF application object. (Note: The OnStartup() method is triggered when the application starts)

5) Overide the OnStartupNextInstance() method to handle future instances. (Note: The OnStartupNextInstance() method is triggered in when another instance of the application starts up)

6) Define a Main entry point for the application and create the wrapper object

7) Create the WPF application class

Sample of the application wrapper

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualBasic.ApplicationServices;
using System.Windows;
 
namespace SingleInstanceApplication
{
    //The Main entry point class
    public class Startup
    {
        [STAThread]
        public static void Main(string[] args)
        {
            SingleInstanceAppWrapper wrapper = new SingleInstanceAppWrapper();
            wrapper.Run(args);
 
        }
    }
 
    //The old-style application wrapper
    public class SingleInstanceAppWrapper : WindowsFormsApplicationBase
    {
        public SingleInstanceAppWrapper()
        {
            // Enable single-instance mode.
            this.IsSingleInstance = true;
        }
 
        // Create the WPF application class.
        private WPFApplication _app;
 
        //Override OnStartup() method to create the WPF application object
        protected override bool OnStartup(
             Microsoft.VisualBasic.ApplicationServices.StartupEventArgs e)
        {
            _app = new WPFApplication();
 
            _app.Run();
 
            return false;
 
        }
 
        // Override OnStartupNextInstance() to handle multiple application instances.
        protected override void OnStartupNextInstance(
             Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs e)
        {
            //In case of command line arguments, send them to the WPF application object    
            if (e.CommandLine.Count > 0)
            {
                _app.HandleCommandLine(e.CommandLine);
            }
 
 
        }
    }
}

As you can see, the sample above contains the Main entry point for the application. This is required because the wrapper must be created first.
If Visual Studio is used, by default the App.xaml application definition style is used. This will not work with the wrapper because the App.xaml approach already has a Main entry point.
Remove App.xaml and App.xaml.cs from the project and create a new class for the entry point.


The only thing left to do is to create the WPF application definition:



public class WPFApplication : System.Windows.Application
{
 
    //Override the OnStartup() method
    protected override void OnStartup(System.Windows.StartupEventArgs e)
    {
        base.OnStartup(e);
        
        //Load the main window
        Window _MainWindow = new Window();
        _MainWindow.Show();
 
        //Set the MainWindow property for the WPF application object
        this.MainWindow = _MainWindow;
 
    }
 
    //Method used to handle command line arguments
    public void HandleCommandLine (System.Collections.ObjectModel.ReadOnlyCollection<string> e)
    {
        //Code to handle command line arguments from other instances goes here
        
    }
 
}

Because the wrapper approach does not contain a XAML application definition (App.xaml), if you need to load application level resources, the following code can be placed the OnStartup() of the WPF application definition to load the resources from a resource dictionary:



 
        Application.Current.Resources.MergedDictionaries.Add(
            Application.LoadComponent(
                new Uri("AssemblyName;component/ApplicationResourceDictionary.xaml",
                UriKind.Relative)) as ResourceDictionary);

The above code will work for dynamic resource definitions. The static resource lookup process will fail because the source for the application resources dictionary need to be specified. In that case the code to load the resources will be replaced with the following:



Application.Current.Resources.Source = 
    new Uri("/AssemblyName;component/ApplicationResourceDictionary.xaml", UriKind.Relative);

Note: AssemblyName is a placeholder for the actual assembly name. The Uri for the resource dictionary location can be changed as required.

Labels: , , , , ,


Comments:
thank you for putting resolving Application Resources part.
 
From this post you will get some info on how to write essay about other countries educational programs and systems. Make sure to check it out as soon as possible
 
Make your Southwest flying experience more special with our amazing deals and premium services, call at Southwest Reservations Number now.

 
wow it really works.interesting.First Copy luxury watches online
 
I am really impressed by your blog.QuickBooks gives you reminder feature in the business with finest version of Quickbooks software to manage all financial transactions.Quickbooks tech support
 
I will be interested in more similar topics. i see you got really very useful topics , i will be always checking your blog thanks
HD Wallpapers
 
Thanks for sharing such useful information and I really appreciate your work, just keep sharing such informative content and I am also a blogger. if you want to travel in your budget then you can visit our Flights from Chicago to New York website where you can easily reserve your flight seats.
 
Your blog is very valuable which you have shared here about 24 hr locksmith near me I appreciate your efforts which you have put into this article and also it is a gainful article for us. Thank you for sharing this article here.
 
One of the common ways to achieve the betting game of Sattaking gali disawar is to effectively combine players prediction and customary sense while betting. It’s satta king’s assumption which will produce the results, but one has got to use guesswork and customary sense to urge the simplest results. Experts of satta king can help players by providing various sorts of tips also as satta king charts like the disawar satta charts for players benefit.
 
Sattakingagency online is a kind of gambling or lottery that started before India's independence. Satta Matka, Sattaking is a full-fledged lottery game that began in the 1950s. Now, it is a very popular game. Though gambling is illegal in India, still many people participate to try their luck. There are some lotteries and horse racing games that are legal in the country.
 
Interesting topic keep sharing such a nice information. Thanks a lot.

99CarRentals
 
This comment has been removed by the author.
 
Nice Blogs!
Thanks for sharing this informative blog.
Car keys solution Melbourne understands how aggravating it may be to require a new car key right away. The good news is that you’ve discovered 24 hour lock smith in Melbourne! We provide a wide range of car key replacement services for all categories of vehicles, including motorcycles and trucks.
https://www.carkeyssolutionmelbourne.com.au/24-hour-lock-smith-melbourne/

 
Online Casino Games For Sale - CadangPintar
The งานออนไลน์ newest online casino in Singapore. The CadangPintar collection. The latest 샌즈카지노 slots, table games and live casino games are also on offer at the 온카지노
 
This comment has been removed by the author.
 
Great post, your all points fully clarify These steps are helpful for Thank you for providing such a valuable information. sattaking
 
Thanks for share this, But WPF does not provide a native solution for single instance applications.Now its time to avail grocery store near mefor more details.


 
Thank you so much for sharing all this wonderful information It is so appreciated. Visit Now.

Buy Shindig by Jonathans

Buy Fireworks online UK

 
Single Instance Applications in WPF ensure that only one instance of the application runs at a time. This is typically achieved using Mutex or Windows Application IDs. It improves user experience by preventing redundant instances and helps manage resources efficiently. Implementing single-instance logic also allows streamlined inter-instance communication.Thank you so much for sharing all this wonderful information It is so appreciated. Visit Now.
Nueva Jersey Violencia Doméstica

 
Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?