Run one instance from the application

前端 未结 7 945
盖世英雄少女心
盖世英雄少女心 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:42

    We had exactly the same problem. We tried the process approach, but this fails, if the user has no right to read information about other processes, i.e. non-admins. So we implemented the solution below.

    Basically we try to open a file for exclusive reading. If this fails (because anohter instance has already done this), we get an exception and can quit the app.

            bool haveLock = false;
            try
            {
                lockStream = new System.IO.FileStream(pathToTempFile,System.IO.FileMode.Create,System.IO.FileAccess.ReadWrite,System.IO.FileShare.None);
                haveLock = true;
            }
            catch(Exception)
            {
                System.Console.WriteLine("Failed to acquire lock. ");
            }
            if(!haveLock)
            {
                Inka.Controls.Dialoge.InkaInfoBox diag = new Inka.Controls.Dialoge.InkaInfoBox("App has been started already");
                diag.Size = new Size(diag.Size.Width + 40, diag.Size.Height + 20);
                diag.ShowDialog();
                Application.Exit();
            }
    
    0 讨论(0)
提交回复
热议问题