How to make sure that there is one instance of the application is running

陌路散爱 提交于 2019-12-03 03:21:52
Pete OHanlon

The most common pattern for doing this is to use the Singleton pattern. As you haven't indicated a language, I'm going to assume that you are referring to C# here - if not, the principles are still the same in most OO languages.

This article should give you some help.

This is something I've used... (C# on .NET 2.0)

    [STAThread]
    private static void Main(string[] args)
    {
        //this follows best practices on
        //ensuring that this is a single instance app.
        string mutexName = "e50cf829-f6b9-471e-8d9f-67eac3699f09";
        bool grantedOwnership;
        //we prefix the mutexName with "Local\\" to allow this to run under terminal services.
        //The "Local\\" prefix forces this into local user space.
        //If we want to forbid this in TS, use the "Global\\" prefix.
        Mutex singleInstanceMutex = new Mutex(true, "Global\\" + mutexName, out grantedOwnership);
        try
        {
            if (!grantedOwnership)
            {
                MessageBox.Show("Error: X is already running.\n\nYou can only run one copy of X at a time.", "X", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
                Application.Exit();
            }
            else
            {
                Application.Run(new X(args));
            }
        }
        finally
        {
            singleInstanceMutex.Close();
        }
    }

In VB .NET there's a IsSingleInstance boolean property that does the job for you.

In VB (taken from here):

Public Class Program
        Inherits Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase

       Public Sub New()
            Me.IsSingleInstance = True
        End Sub



End Class

Here's how you use it in C# (taken from here):

// SingleInstanceApplication.cs
class SingleInstanceApplication : WindowsFormsApplicationBase {

 // Must call base constructor to ensure correct initial 
 // WindowsFormsApplicationBase configuration
 public SingleInstanceApplication() {

  // This ensures the underlying single-SDI framework is employed, 
  // and OnStartupNextInstance is fired
  this.IsSingleInstance = true;
 }
}


// Program.cs
static class Program {
 [STAThread]
 static void Main(string[] args) {
  Application.EnableVisualStyles();
  SingleInstanceApplication application = 
   new SingleInstanceApplication();
  application.Run(args);
 }
}

Make sure to reference the Microsoft.VisualBasic.dll in your project.

Open your Project Properties (Application Tab) and check the Make single instance application option.

From the Application tab, you can also click the View Application Events button, to create an ApplicationEvents.vb class where you can handle the second instance event:

Partial Friend Class MyApplication
    Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
        ' Bring First Instance to Foreground
        e.BringToForeground = True
        ' Pass Second Instance Command Line to First Instance
        AppShared.DoSomethingWithCommandLine(e.CommandLine)
    End Sub
End Class

Scott Hanselman has nice article about this. The code is in C# but I guess it'll be easy to port it to VB.

http://www.hanselman.com/blog/TheWeeklySourceCode31SingleInstanceWinFormsAndMicrosoftVisualBasicdll.aspx

Here's one more article on the topic in case that won't meet your needs:

http://www.codeproject.com/KB/cs/cssingprocess.aspx

In VB.NET, a single instance app is just a checkbox on the Project property page. You can also trap the My.Application.StartupNextInstance event to have your single instance do something when another copy is launched. This can be used, for example, for MDI like behavior of opening the requested document in the original instance.

Behind the scenes, this encapsulates a good bit of mutex and IPC goo - see WindowsFormApplicationBase - and can be used from C# as well.

Through the tips above, I found out how to make my app a single instance, but I still had to go to another site to find out EXACTLY how. Here is a simple picture how I managed to do that. It was easy-peasy and I hope it helps others with the same need because I'm sure the OP solved this problem 7 years ago:

Use Mutex. Effectively, a Mutex can be named with a string, and is unique across the CLR.

Sample code:

try
{
mutex = Mutex.OpenExisting(mutexName);
//since it hasn’t thrown an exception, then we already have one copy of the app open.
MessageBox.Show(”A copy of Todo 3.0 is already open. Please check your system tray (notification area).”,
“Todo 3.0″, MessageBoxButtons.OK, MessageBoxIcon.Information);
Environment.Exit(0);
}
catch (Exception Ex)
{
//since we didn’t find a mutex with that name, create one
Debug.WriteLine(”Exception thrown:” + Ex.Message + ” Creating a new mutex…”);
mutex = new Mutex(true, mutexName);
}

From this post:

If your application is in VB.NET 2.0-3.5, the easiest way to keep a single instance of the program running is by using the 'Windows Application Framework Properties'. To get there, right-click on your project name and go to 'Properties'. Once there, select the 'Make single instance appliation' checkbox.

You can also use the ApplicationEvents.vb to show the user that they have run your program a second time. You can create/view that easily in the same properties window by selecting the 'View Application Events' button. Within there, you can select the MyApplication_StartupNextInstance sub and enter in code there, like this:

Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
    MessageBox.Show("This program is already running.  If you do not see the program running, please check your " _
        & "Windows Task Manager for this program name in the 'Processes' Tab." & vbNewLine & vbNewLine & "WARNING: " _
        & " If you terminate the process, you will terminate the only instance of this program!", My.Application.Info.ProductName.ToString _
        & " is Running!", MessageBoxButtons.OK, MessageBoxIcon.Warning)

End Sub

Let me know if this helps! JFV

Assign your app some unique identifier, such as a hardcoded guid and create a Mutex instance where you assign the mutex it that identifier. If it throws an exception then if means your application is already running (as it successfully managed to create the mutex)

I thought it would be easier to have the sample right here instead of a link.

    [STAThread]
    static void Main()
    {
        if (!IsAppAlreadyRunning())
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1()); /* Change Form1 for your main Form */
        }
        else
        {
            MessageBox.Show("Application is already running!");
        }
    }

    public static bool IsAppAlreadyRunning()
    {
        Process currentProcess = Process.GetCurrentProcess();
        return (IsAppAlreadyRunning(currentProcess.Id, 
                                    currentProcess.ProcessName));
    }

    private static bool IsAppAlreadyRunning(int ID, string Name)
    {
        bool isAlreadyRunning = false;
        Process[] processes = Process.GetProcesses();
        foreach (Process process in processes)
        {
            if (ID != process.Id)
            {
                if (Name == process.ProcessName)
                {
                    isAlreadyRunning = true;
                    break;
                }
            }
        }
        return isAlreadyRunning;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!