Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make it so if one copy of a program is running another won't be able to open?

Tags:

c#

.net

How to make it so if one copy of a program is running another won't be able to open?

Or better yet, how to make it so that if one copy is already running, then trying to run another copy will just act as if you maximized the original process?

like image 378
Alex Baranosky Avatar asked Jan 24 '23 21:01

Alex Baranosky


2 Answers

Scott Hanselman wrote a post on doing this sort of thing

like image 162
Garry Shutler Avatar answered Jan 26 '23 12:01

Garry Shutler


This article

True Single instance application - WinForms.NET

explains how to create a true single instance:

This article simply explains how you can create a windows application with control on the number of its instances or run only single instance. This is very typical need of a business application. There are already lots of other possible solutions to control this.

e.g. Checking the process list with the name of our application. But this methods don't seems to be a good approach to follow as everything is decided just on the basis on the application name which may or may not be unique all across.

using System;
using Microsoft.VisualBasic.ApplicationServices;

namespace Owf
{
  public class SingleInstanceController
    : WindowsFormsApplicationBase
  {
    public SingleInstanceController()
    {
      // Set whether the application is single instance
      this.IsSingleInstance = true;

      this.StartupNextInstance += new 
        StartupNextInstanceEventHandler(this_StartupNextInstance);
    }

    void this_StartupNextInstance(object sender, 
                      StartupNextInstanceEventArgs e)
    {
      // Here you get the control when any other instance is 
      // invoked apart from the first one. 
      // You have args here in e.CommandLine.

      // You custom code which should be run on other instances
    }

    protected override void OnCreateMainForm()
    {
      // Instantiate your main application form
      this.MainForm = new Form1();
    }
  }
}

Change you main function this way:

[STAThread]
static void Main()
{
  string[] args = Environment.GetCommand
  SingleInstanceController controller = new SingleInstanceController();
  controller.Run(args);
}
like image 36
splattne Avatar answered Jan 26 '23 10:01

splattne