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;
}
The ProcessName property holds an executable file name, such as Outlook, that does not include the .exe extension or the path. It is helpful for getting and manipulating all the processes that are associated with the same executable file.
The process name is used to register application defaults and is used in error messages. It does not uniquely identify the process. User defaults and other aspects of the environment might depend on the process name, so be very careful if you change it. Setting the process name in this manner is not thread safe.
Try with this :
Process p = Process.GetCurrentProcess();
string cMyProcessName = p.ProcessName;
Process.GetCurrentProcess Method is what you need :
string processName = Process.GetCurrentProcess().ProcessName;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With