Skip to content

Instantly share code, notes, and snippets.

@miteshsureja
Last active May 27, 2018 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miteshsureja/4a577b200a4eda57ae27fff2e53f4430 to your computer and use it in GitHub Desktop.
Save miteshsureja/4a577b200a4eda57ae27fff2e53f4430 to your computer and use it in GitHub Desktop.
How to run single instance of an application using Mutex?
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
namespace WPFSingleInstanceApplication
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private static Mutex mutex = null;
protected override void OnStartup(StartupEventArgs e)
{
bool isFirstInstance;
mutex = new Mutex(true, "MyWPFApp", out isFirstInstance);
if (isFirstInstance)
{
MessageBox.Show("Welcome, Running first instance of MyWPFApp", "Info");
MainWindow window = new MainWindow();
window.Show();
}
else
{
MessageBox.Show("One instance of MyWPFApp is already running.", "Info");
Application.Current.Shutdown();
}
base.OnStartup(e);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SingleInstanceApplication
{
class Program
{
static void Main(string[] args)
{
bool isFirstInstance;
using (Mutex mutex = new Mutex(true, "MyApp", out isFirstInstance))
{
if (isFirstInstance)
{
Console.WriteLine("Welcome, Running first instance of MyApp.");
Console.Read();
}
else
{
Console.WriteLine("One instance of MyApp is already running.");
Console.Read();
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SingleInstanceApplication
{
class Program
{
static void Main(string[] args)
{
//get process count of running application
if (System.Diagnostics.Process.GetProcessesByName(
System.IO.Path.GetFileNameWithoutExtension(
System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1)
{
Console.WriteLine("One instance is already running so closing this instance.");
Console.Read();
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
else
{
Console.WriteLine("Welcome, Running first instance.");
Console.Read();
}
}
}
}
@miteshsureja
Copy link
Author

image
image

@miteshsureja
Copy link
Author

image
image

@miteshsureja
Copy link
Author

image
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment