Run one instance from the application

前端 未结 7 951
盖世英雄少女心
盖世英雄少女心 2020-12-16 06:49

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 appl

7条回答
  •  春和景丽
    2020-12-16 07:33

    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
    {
        /// 
        /// The main entry point for the application.
        /// 
        [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");
        }
    }
    

提交回复
热议问题