为什么使用windows任务栏图标切换应用程序时System.Diagnostic.Process抛出异常?

Why does System.Diagnostic.Process throw exception when switching apps using windows task bar icon?

我目前正在开发一个应用程序,该应用程序使用 System.Diagnostics.Process 获取当前活动应用程序或前台应用程序的 Window 标题。现在,这很好,并且可以使用我现有的代码,直到我遇到这个问题。如果我使用任务栏图标而不是应用程序的最小化按钮切换我的应用程序 window。

,则会发生此 NullReferenceException

编辑: 如果我不提出来,可能会造成混淆。所以基本上 NullReferenceException 是由 (title.Equals(System.Diagnostics.Process.GetCurrentProcess().MainWindowTitle))

引起的

由于

title 变量为空
String title = GetActiveWindowTitle();

GetActiveWindowTitle() returns 无效。这使用 Window.GetForegroundWindow(); 并且出于某种原因使用任务栏图标来切换,这个 Window.GetForegroundWindow(); 方法 returns 没什么。

原来我用这个

[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();

为了得到我需要的东西。但是在使用任务栏图标切换应用程序时,我仍然遇到同样的问题。使用此代码的唯一区别是异常是这个 A first chance exception of type 'System.ComponentModel.Win32Exception' occurred in System.dll

我的操作系统是Windows8.1.

非常感谢任何意见。

更新 @KcDoD 的回答有些正确。由于 NullReferenceException 实际上是我问题的一部分,我将其标记为答案。它也指导我弄清楚发生了什么。

基本上,在我的应用程序中,我在 WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime) 中调用此方法 GetActiveWindowTitle()。 WinEventProc() 是一个委托方法,在您切换 window 时触发。事实证明,通过调用 GetForegroundWindow();GetActiveWindowTitle() 进程尚未激活,这就是为什么当它去获取活动应用程序或处理它时 gives/return null.

此致

您的问题与您试图与 MainWindowTitle 相等的字符串有关。也就是说titlevariable/field。

在尝试使用 Equal

之前,您应该检查 tite 是否有 null

另外:这是一个使用 here

答案的程序
  static void Main(string[] args)
  {
      String answ;

      while (true)
      {
           answ = GetActiveWindowTitle();
           if (answ == null)
           {
               Console.WriteLine("NO active program");
           }
           else {
              Console.WriteLine(answ);
           }
        Thread.Sleep(1000);
       }

 }


 [DllImport("user32.dll")]
 static extern IntPtr GetForegroundWindow();

 [DllImport("user32.dll")]
 static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

 static private string GetActiveWindowTitle()
 {
    const int nChars = 256;
    StringBuilder Buff = new StringBuilder(nChars);
    IntPtr handle = GetForegroundWindow();

    if (GetWindowText(handle, Buff, nChars) > 0)
    {
        return Buff.ToString();
     }
     return null;
  }

答案:如果没有选择任何进程,那么这将 return 为空。我想这就是你问题的答案。