2017-07-27 113 views
-1

此之前已經問過了,這裏有一些我已經嘗試了其他問題,但一直沒有實現:如何檢查哪個進程當前具有焦點

Determine if current application is activated (has focus)

C#: Detecting which application has focus

How can i get application name which is currently focused

我目前沒有工作:

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

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
    public static extern int GetWindowThreadProcessId(IntPtr handle, out int processId); 
} 

public static bool ApplicationIsActivated() 
{ 
    try 
    { 
     var activatedHandle = User32.GetForegroundWindow(); 
     if (activatedHandle == IntPtr.Zero) 
     { 
     // No window is currently activated 
     return false; 
     } 

     var procId = Process.GetCurrentProcess().Id; 
     int activeProcId; 
     User32.GetWindowThreadProcessId(activatedHandle, out activeProcId); 

     return activeProcId == procId; 
    } 
    catch(Exception ex) 
    { 
     Console.WriteLine(ex); 
    } 
} 

static void Main(string[] args) 
{ 
    try 
    { 
     while (true) 
     { 
      if (ApplicationIsActivated()) 
       CaptureApplication(); 
      Thread.Sleep(3000); 
     } 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex); 
    } 
} 

我想檢查的是當前是否有焦點的進程WINWORD。我在我的程序的其他地方有一些代碼實際上使用Process.GetProcessesByName("WINWORD")[0];,但我無法弄清楚如何檢查WINWORD是否有重點。

編輯:在調試過程中,我發現activeProcID確實有正確的進程ID,但procID包含進程ID,我在CMD中運行tasklist /svc時看不到。

+1

GetCurrentProcess是應用程序的過程 - 所以基本上你的代碼檢查,如果你的進程有活動窗口。您是否嘗試過使用「var procId = Process.GetProcessesByName(」WINWORD「)。FirstOrDefault()?. Id;」 – ckuri

+0

感謝您的想法,我沒有意識到'GetProcessById'上有更多擴展有一個方法'.ProcessName'完美的工作,我已經公佈解決方案作爲答案。 –

回答

0

這裏是我的解決方案:

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

[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
public static extern int GetWindowThreadProcessId(IntPtr handle, out int processId); 

public static bool ApplicationIsActivated() 
{ 
    var activatedHandle = User32.GetForegroundWindow(); 
    if (activatedHandle == IntPtr.Zero) 
    { 
     // No window is currently activated 
     return false; 
    } 

    var procId = Process.GetCurrentProcess().Id; 
    int activeProcId; 

    User32.GetWindowThreadProcessId(activatedHandle, out activeProcId); 
    string activeProcName = Process.GetProcessById(activeProcId).ProcessName.ToString(); 

    if (activeProcName.Equals("WINWORD")) 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 

爲什麼這個工程:

Process.GetProcessById(activeProcId).ProcessName.ToString();

相關問題