简体   繁体   中英

What is the safest way to prevent multiple instances of a program?

I am trying to prevent my program from running multiple instances at any given time. I have read about using mutex and windows events, however both threads were several years old, and I'm curious if with .net4 there is a more simple, and more elegant way to deal with this? I thought I had read about a setting for the form that allowed you to deny multiple instances by the property? Could someone shed some light on what the safest and/or simplest way to prevent multiple instances of a program is?

The safest way is to use the built-in support in .NET, WindowsFormsApplicationBase.IsSingleInstance property. Hard to guess if it is appropriate, you didn't make much effort describing your exact needs. And no, nothing changed in the past 5 years. – Hans Passant Jan 7 at 0:38

This was the best answer but Hans didn't submit it as an answer.

In VB you can set this at the project level (Properties > General) for Winforms projects.

In C# you can use code similar to this.. needs conversion of course..

Dim tGrantedMutexOwnership As Boolean = False
Dim tSingleInstanceMutex As Mutex = New Mutex(True, "MUTEX NAME HERE", tGrantedMutexOwnership)

If Not tGrantedMutexOwnership Then
'
' Application is already running, so shut down this instance
'
Else
' 
' No other instances are running
'
End If

Whoops, I forgot to mention that you will need to place GC.KeepAlive(tSingleInstanceMutex) after your Application.Run() call

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;

namespace YourNameSpaceGoesHere
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {

            if (Process.GetProcessesByName("YourFriendlyProcessNameGoesHere").Length > 1)
            {
                MessageBox.Show(Application.ProductName + " already running!");
                Application.ExitThread();
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new YourStartUpObjectFormNameGoesHere());
            }

        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM