Thursday, August 14, 2014

Code to create a single instance of WPF application



Code to create a Single instance of Windows Application in WPF
To create a single instance first we need to check if there is any instance is already running and kills the current process to stop creating multiple instances. This can be achieved by the below code.  

using System;
using System.Diagnostics;
using System.IO;
namespace SingleInstance
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            var exists = Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count();

            if(exists > 1)
            {
                MessageBox.Show("An Instance of the application is already running");               
                System.Diagnostics.Process.GetCurrentProcess().Kill();
                return;
            }

            InitializeComponent();
        }
    }
}


No comments:

Post a Comment