Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run one instance from the application

Tags:

c#

semaphore

I have a windows application (C#) and i need to configure it to run one instance from the application at the time , It means that one user clicked the .exe file and the application is run and the user didn't close the first instance of the application that is being run and need to run a next instance so it should appear the first instance and not opening new one.

can any one help me how to do that?

thanks in advance

like image 836
Ahmy Avatar asked Dec 05 '22 06:12

Ahmy


2 Answers

I often solve this by checking for other processes with the same name. The advantage/disadvantage with this is that you (or the user) can "step aside" from the check by renaming the exe. If you do not want that you could probably use the Process-object that is returned.

  string procName = Process.GetCurrentProcess().ProcessName;
  if (Process.GetProcessesByName(procName).Length == 1)
  {
      ...code here...
  }

It depends on your need, I think it's handy to bypass the check witout recompiling (it's a server process, which sometimes is run as a service).

like image 152
kaze Avatar answered Dec 09 '22 16:12

kaze


The VB.Net team has already implemented a solution. You will need to take a dependency on Microsoft.VisualBasic.dll, but if that doesn't bother you, then this is a good solution IMHO. See the end of the following article: Single-Instance Apps

Here's the relevant parts from the article:

1) Add a reference to Microsoft.VisualBasic.dll 2) Add the following class to your project.

public class SingleInstanceApplication : WindowsFormsApplicationBase
{
    private SingleInstanceApplication()
    {
        base.IsSingleInstance = true;
    }

    public static void Run(Form f, StartupNextInstanceEventHandler startupHandler)
    {
        SingleInstanceApplication app = new SingleInstanceApplication();
        app.MainForm = f;
        app.StartupNextInstance += startupHandler;
        app.Run(Environment.GetCommandLineArgs());
    }
}

Open Program.cs and add the following using statement:

using Microsoft.VisualBasic.ApplicationServices;

Change the class to the following:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        SingleInstanceApplication.Run(new Form1(), StartupNextInstanceEventHandler);
    }

    public static void StartupNextInstanceEventHandler(object sender, StartupNextInstanceEventArgs e)
    {
        MessageBox.Show("New instance");
    }
}
like image 36
Kim Major Avatar answered Dec 09 '22 15:12

Kim Major