I'm currently developing an app that uses System.Diagnostics.Process
to get the Window Title of the Current Active App or the App on the ForeGround. Now, this is fine and working with the current code I have until I came across with this issue. This NullReferenceException
occurs if I switch my app using the task bar icon instead of the minimized button of the app window.
Edit:
It maybe confusing if I don't raise this up. So basically NullReferenceException
is caused by (title.Equals(System.Diagnostics.Process.GetCurrentProcess().MainWindowTitle))
title variable is null due to
String title = GetActiveWindowTitle();
GetActiveWindowTitle() returns null. And this uses Window.GetForegroundWindow();
And for some reason using taskbar icons to switch up, this Window.GetForegroundWindow();
method returns nothing.
Originally I used this
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
To get what I need. But I'm still having the same issue when switching app using the task bar icon. The only difference with using this code is that the exception is this
A first chance exception of type 'System.ComponentModel.Win32Exception' occurred in System.dll
My operating system is Windows 8.1.
Any inputs is greatly appreciated.
Update
The answer from @KcDoD was somewhat correct. And since the NullReferenceException
was actually part of my question I will mark it as the Answer. And it also guides me a lot to figure out what's going on.
Basically, on my application I call this method GetActiveWindowTitle()
within WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
. WinEventProc() is a delegate method that triggers when you switch window. And it turns out that by calling GetForegroundWindow();
or GetActiveWindowTitle()
the process is not active yet that's why when it goes to get the Active application or Process it gives/return null.
Best regards