2014-03-30 281 views
0

我想這樣做...如果記事本是在前臺它打開計算器...如果另一個程序打開什麼都不做......記事本是oepn manualy ...「啓動記事本」 ......我有這樣的代碼來‘看’如果Notepad已經打開......不知道如何繼續d:我知道我必須使用比較字符串進程名稱

if (switch == 0) 
{ 
if (SOMETHING == "Notepad") 
{ 
    var switch = 1 //so it doesnt enters in a loop 
    OPEN CALCULATOR //irrelevant, i may use another part of otrher code that is already working 
    } 
} 

‘開關’變量會從代碼的開頭爲0,這樣去上班(希望)

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] 
public static extern IntPtr GetForegroundWindow(); 

[DllImport("user32.dll", SetLastError = true)] 
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId); 

Process GetActiveProcess() 
{ 
    IntPtr hwnd = GetForegroundWindow(); 
    uint pid; 
    GetWindowThreadProcessId(hwnd, out pid); 
    Process p = Process.GetProcessById((int)pid); 
    return p; 
} 

的問題是,我不知道該穿什麼「東西」給我們E中的代碼的其餘部分,以及在哪裏或如何使用如果...

回答

1

你可以這樣做:

Process[] notePadProcesses = Process.GetProcessesByName("notepad.exe"); 
IntPtr activeWindowHandle = GetForegroundWindow(); 

if (notePadProcesses != null && notePadProcesses.Length > 0 
    && notePadProcesses.Any(p=>p.MainWindowHandle == activeWindowHandle)) 
{ 
// notepad is open in the foreground. 
switch = 1; 
// OPEN Calculator or whatever you need to. 
} 
else 
{ 
// notepad is either not open, or not open in the foreground. 
} 

基本上我們使用C#友好的工藝類,以找到所有打開記事本程序。 然後找到它是否是一個活動進程並從那裏開始。

請小心使用activewindow邏輯,因爲很多時候,它們會導致競爭條件,當您確定進程處於活動狀態並嘗試執行某些操作時,它可能不再是活動進程。仔細踩踏。

+0

不工作...我沒有找到「任何」的問題(加下劃線的紅色,這是錯誤) 'System.Array /'不包含'任何'的定義,也沒有任何擴展方法'任何'接受'System.Array'類型的第一個參數可以找到(你是否缺少使用指令或程序集引用?) 我的「使用」是這樣的 – user3471081

+0

我錯過了somethingn:p THAAANKS愛你:D它已經三天試圖做到這一點..ñ – user3471081

+0

不woring如何應該...程序開始...做任何事已經做了...沒辦法知道什麼是錯的... – user3471081