是否有可能获得自己的进程名称?

Nik*_*las 4 c# process

我想替换cMyProcessName(在我的例子中)编程,我不想使用sting常量!

这是代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

ale*_*oot 7

试试这个:

Process p = Process.GetCurrentProcess();    
string cMyProcessName = p.ProcessName;
Run Code Online (Sandbox Code Playgroud)