Search code examples
c#interopmessagehwnd

C# HwndSource from Process.MainWindowHandle


I am trying to "hook" in to the messages of a window to detect a minimize/maximize. I've looked around, and think that the only/best solution to do this, is to hook into the messages of a window, and check for the WM_WINDOWPOSCHANGED message, and then check it's status.

I've run into a problem.

System.Windows.Interop.HwndSource source = System.Windows.Interop.HwndSource.FromHwnd(System.Diagnostics.Process.GetProcessesByName("notepad")[0].MainWindowHandle);
System.Windows.Interop.HwndSourceHook hook = new System.Windows.Interop.HwndSourceHook(WndProc);
source.AddHook(hook);

It will give me a "Object refrence not set to the instance of an object." error on "source.AddHook...". When breakpointing, it also becomes clear that the source variable is null. In other words: It fails to get the HwndSource on the first line.

I know that it's possible by using an "WindowInteropHelper", but that is when you have the actual window as a Windows.Window available, but in my situation I do not.

Any workarounds/solutions would be very much appreciated,
René Sackers

P.S. I am 100% sure that Notepad is running when the code is executed, and it manages to find it, and it's main window handle.


Solution

  • HwndSource and HwndSourceHook don't do what you are thinking. They only exist for interop between WPF and standard Win32 windows - in the same process. They can't be used for hooking the window procedure of a window in a different process.

    HwndSource.FromHwnd() doesn't create a new HwndSource object it "Returns the HwndSource object of the specified window." If the hWnd doesn't have one it associated, FromHwnd() will return null. It would be like calling System.Windows.Forms.Control.FromHandle on the hWnd from notepad - which would return null as well since the notepad window isn't a WinForms control.

    The way to hook another process's window procedure is to use SetWindowsHookEx. And for to hook another process, the code has to be written in C or C++.