Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifying own process name in C#

Tags:

c#

process

To prevent user from running multiple instances of my application, I am using this code:-

 Process[] pArry = Process.GetProcesses();
           int nCount = 0;
           foreach (Process p in pArry)
           {
               string ProcessName = p.ProcessName;
               ProcessName = ProcessName.ToLower();
               if (ProcessName.CompareTo("myApp") == 0)
               {
                   nCount++;
               }
           }   
           if (nCount > 1)
           {
               MessageBox.Show(AppAlreadyRunning,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
               Process.GetCurrentProcess().Kill();
           }

But As we know, Process Name changes if change the exe name. So If user changes "myApp.exe" to "UserApp.exe", This patch won't work! Is there any way out?

I am using C# in VS2010. Thanks!

like image 566
Swanand Avatar asked Dec 16 '22 15:12

Swanand


2 Answers

This is very simple process. Calling this function returns a process class with all the information you need.

Process.GetCurrentProcess()

Here is some code for you.

       Process[] pArry = Process.GetProcesses();
       foreach (Process p in pArry)
       {
           if (p.Id == Process.GetCurrentProcess().Id)
                continue;
           string ProcessName = p.ProcessName;
           if(ProcessName == Process.GetCurrentProcess().ProcessName)
           {
                MessageBox.Show(AppAlreadyRunning,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error)
                SetForegroundWindow(p.MainWindowHandle);
                Application.Exit();
           }
       }   
like image 96
Craig White Avatar answered Jan 05 '23 00:01

Craig White


These questions seems quite similar...

https://stackoverflow.com/questions/93989/prevent-multiple-instances-of-a-given-app-in-net

https://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567

like image 37
JeremyWeir Avatar answered Jan 05 '23 01:01

JeremyWeir