5

I want to replace cMyProcessName (in my example) programatic, i dont want to use a sting constant !

This is the code:

private const string cMyProcessName = "MyProcessName";

if (GetProcessCount(cMyProcessName) > 1)
{
    System.Threading.Thread.Sleep(2000); //Give it some time (if just restarted)
    //**************************************************************//
    if (GetProcessCount(cMyProcessName) > 1)
    {
        MessageBox.Show("MyProcessName is already running. Exiting.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }
    //**************************************************************//
}

public static int GetProcessCount(string processName)
{
    Process[] ps = Process.GetProcessesByName(processName);

    return ps.Length;
}
RvdK
  • 19,580
  • 4
  • 64
  • 107
Niklas
  • 1,753
  • 4
  • 16
  • 35
  • possible duplicate of [prevent a c# application from running more than one instance](http://stackoverflow.com/questions/3545240/prevent-a-c-sharp-application-from-running-more-than-one-instance) – Steve B Dec 08 '11 at 08:38
  • (it was not the case, i just wanted the process name) – Niklas Dec 08 '11 at 11:16

3 Answers3

9

Try with this :

Process p = Process.GetCurrentProcess();    
string cMyProcessName = p.ProcessName;
aleroot
  • 71,077
  • 30
  • 176
  • 213
1

Process.GetCurrentProcess Method is what you need :

string processName = Process.GetCurrentProcess().ProcessName;
Steve B
  • 36,818
  • 21
  • 101
  • 174
1

you can probably simplify your code very much by using:

Process currentProcess = Process.GetCurrentProcess();

see here: Process.GetCurrentProcess Method

Davide Piras
  • 43,984
  • 10
  • 98
  • 147