The Single Instance Class Library
If the user tries to run a second copy of the application, the existing instance should kill itself.

Introduction
Sometimes, we do not want to run the same copy of the application. Here in this case, you can use the single instance class library. This library includes a static
function. This function detects a second copy of the application that is already running. If the user tries to run a second copy of the application, the existing instance should kill itself.
Using the Code
Single Instance Class Library C# Code
using System.Diagnostics;
namespace SingleInstance
{
public class SingleInstance
{
/// <summary>
/// Detect a second copy of the application that is already running.
/// If the user tries to run a second copy of the application,
/// the existing instance should kill itself.
/// </summary>
public static void SingleInst()
{
if (Process.GetProcessesByName
(Process.GetCurrentProcess().ProcessName).Length > 1)
Process.GetCurrentProcess().Kill();
}
}
}
Single Instance Class Library MC++ Code
namespace SingleInstance
{
public __gc class SingleInstance
{
/// <summary>
/// Detect a second copy of the application that is already running.
/// if the user tries to run a second copy of the application,
/// the existing instance should kill itself.
/// </summary>
public: static void __gc* SingleInst()
{
if (Process::GetProcessesByName
(Process::GetCurrentProcess()->ProcessName)->Length > 1)
{
Process::GetCurrentProcess()->Kill();
}
}
};
}
Single Instance Class Library VB Code
Imports System
Imports System.Diagnostics
Namespace SingleInstance
Public Class SingleInstance
' <summary>
' Detect a second copy of the application that is already running.
' if the user tries to run a second copy of the application,
' the existing instance should kill itself.
' </summary>
Public Shared Sub SingleInst()
If (Process.GetProcessesByName_
(Process.GetCurrentProcess.ProcessName).Length > 1) Then
Process.GetCurrentProcess.Kill
End If
End Sub
End Class
End Namespace
Console Application Sample Code
using System;
namespace SingleInstConsole
{
class Program
{
static void Main()
{
// Single Instance Application
SingleInstance.SingleInstance.SingleInst();
Console.WriteLine("Merhaba " + Environment.UserName);
Console.ReadLine();
}
}
}
Windows Form Application Sample (Program.cs)
using System;
using System.Windows.Forms;
namespace SingleInstWindowsFormsApp
{
static class Program
{
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
// Single Instance Application
SingleInstance.SingleInstance.SingleInst();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
History
- 2nd May, 2009: Initial post