本文介绍了来自Process.MainWindowHandle的C#HwndSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图钩住"窗口的消息以检测最小化/最大化.我环顾四周,认为实现此目的的唯一/最佳解决方案是挂接到窗口的消息中,并检查WM_WINDOWPOSCHANGED消息,然后检查其状态.

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.

我遇到了问题.

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);

它将给我一个未将对象引用设置为对象实例的信息."关于"source.AddHook ..."的错误.当进行断点操作时,也很清楚源变量为null.换句话说:它无法在第一行上获取HwndSource.

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.

我知道可以通过使用"WindowInteropHelper"来实现,但这就是当您拥有实际的窗口作为Windows.Window可用时,但是在我的情况下我没有.

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.

任何解决方法/解决方案将不胜感激,
雷内·萨克斯(RenéSackers)

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

P.S.我100%确信执行代码后,记事本正在运行,并且设法找到它,并且它是主窗口句柄.

推荐答案

HwndSourceHwndSourceHook并没有按照您的想法进行.它们仅用于WPF和标准Win32窗口之间的互操作-在同一过程中.它们不能用于在其他进程中挂接窗口的窗口过程.

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()不会创建新的HwndSource对象,而是返回指定窗口的HwndSource对象".如果hWnd没有关联,则FromHwnd()将返回null.就像从记事本在hWnd上调用System.Windows.Forms.Control.FromHandle一样-由于记事本窗口不是WinForms控件,它也会返回null.

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.

挂钩另一个进程的窗口过程的方法是使用 SetWindowsHookEx .为了挂接另一个进程,必须使用C或C ++编写代码.

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++.

这篇关于来自Process.MainWindowHandle的C#HwndSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!