Identification of a name of own process in C #

To prevent the user from running multiple instances of my application, I use 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 you know, the name of the process changes if you change the name exe. So, if the user changes "myApp.exe" to "UserApp.exe", this patch will not work! Is there a way out?

I am using C # in VS2010. Thanks!

+4
source share
3 answers
+4
source

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

 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(); } } 
+7
source

I bet you can use Process.GetCurrentProcess () (how you do it to kill a process) to get the actual name and use it for comparison.

+1
source

Source: https://habr.com/ru/post/1347492/


All Articles