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,128
  • 3
  • 59
  • 105
Niklas
  • 1,673
  • 2
  • 16
  • 34
  • 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
  • 68,849
  • 28
  • 172
  • 209
1

Process.GetCurrentProcess Method is what you need :

string processName = Process.GetCurrentProcess().ProcessName;
Steve B
  • 35,764
  • 20
  • 96
  • 161
1

you can probably simplify your code very much by using:

Process currentProcess = Process.GetCurrentProcess();

see here: Process.GetCurrentProcess Method

Davide Piras
  • 43,118
  • 10
  • 90
  • 143