Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get own process name?

Tags:

c#

process

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;
}
like image 934
Niklas Avatar asked Dec 08 '11 08:12

Niklas


People also ask

Is Process name same as EXE name?

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.

What is the process name?

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.


2 Answers

Try with this :

Process p = Process.GetCurrentProcess();    
string cMyProcessName = p.ProcessName;
like image 91
aleroot Avatar answered Oct 15 '22 02:10

aleroot


Process.GetCurrentProcess Method is what you need :

string processName = Process.GetCurrentProcess().ProcessName;
like image 27
Steve B Avatar answered Oct 15 '22 02:10

Steve B