How to restrict a program to a single instance

Restrict single instance of a program. Use of GetProcessesByName method. How to restrict an instance of a program. How to get the instance name of a process.

The following are the steps involved in restricting a program to a single instance :

  1. Create an instance of the Process class to store the current running process. GetCurrentProcess() will create a new process component and assign it to the current process we are running.

  2. Create another instance for Process class.Check whether already the same process in running using GetProcessesByName method.

    GetProcessesByName method creates an array of process and associates them with all the process component that share the specified process name. Check if the length of the array object is greater than one.If it is then current process is already instantiated. Otherwise allow the process to run.

The code sample below follows the above given algorithm judiciously. In this example, we have implemented the algorithm in the Main() function. This can also be treated as a seperate method if necessary. For example, when a user chooses to run a program, say a music player, which is already running, we might not need another instance of the player. Thus, every time a process is instantiated we need to check if it's already running.

static void Main()
Process ThisProcess = Process.GetCurrentProcess();
Process [] AllProcesses = Process.GetProcessesByName(ThisProcess.ProcessName);
if (AllProcesses.Length > 1)
MessageBox.Show(ThisProcess.ProcessName + " is already running",
}else {
Application.Run(new MainForm());


Author: Hefin Dsouza31 Jul 2008 Member Level: Gold   Points : 2

Good Work Here is an Version of the Same Code

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Process.GetProcessesByName(Process.GetCurrentProcess.ProcessName).Length() > 1 Then
MsgBox("This is a Single instance Applicaton " & vbNewLine & "* Another Instance is Already Running", MsgBoxStyle.OKOnly, "Single Instance Application")
End If
End Sub

Thank You

Regards Hefin Dsouza

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: