2011-12-08 56 views
1

我想替換cMyProcessName(在我的例子中)程序化,我不想使用刺常量!是否有可能獲得自己的進程名稱?

這是代碼:

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; 
} 
+0

可能重複(http://stackoverflow.com/問題/ 3545240/prevent-ac-sharp-application-from-running-more-one-instance) –

+0

(事實並非如此,我只想要進程名稱) – Niklas

回答

4

試試這個:

Process p = Process.GetCurrentProcess();  
string cMyProcessName = p.ProcessName; 
+0

你試過這段代碼嗎?你真的可以將它分配給一個const嗎? –

+0

不可能...你不能有一個const動態分配(或它不再是一個常量) –

+0

對不起,我離開了const ... – aleroot

0

使用Process.GetCurrentProcess()從System.Diagnostics程序

0

你也許可以通過簡化你的代碼非常:

Process currentProcess = Process.GetCurrentProcess(); 

在這裏看到:Process.GetCurrentProcess Method

的[防止C#應用程序運行多個實例]
相關問題