对于我正在创建的应用程序,我想拦截来自外部进程的窗口消息(很像spy ++的做法)。我想通了,我可以使用SetWinEventHook来做到这一点。 这是我的代码。C#SetWinEventHook失败(返回0)
class Program
{
internal delegate void WinEventProc(IntPtr hWinEventHook, int iEvent, IntPtr hWnd, int idObject, int idChild, int dwEventThread, int dwmsEventTime);
[DllImport("user32.dll", SetLastError = true)]
internal static extern IntPtr SetWinEventHook(int eventMin, int eventMax, IntPtr hmodWinEventProc, WinEventProc lpfnWinEventProc, int idProcess, int idThread, SetWinEventHookFlags dwflags);
//[DllImport("user32.dll", SetLastError = true)]
internal static extern int UnhookWinEvent(IntPtr hWinEventHook);
internal enum SetWinEventHookFlags
{
WINEVENT_INCONTEXT = 4,
WINEVENT_OUTOFCONTEXT = 0,
WINEVENT_SKIPOWNPROCESS = 2,
WINEVENT_SKIPOWNTHREAD = 1
}
static void Main(string[] args)
{
int threadId = 0x000306D4;
int processId = 0x000306BC;
WinEventProc listener = new WinEventProc(EventCallback);
//setting the window hook and writing the result to the console
Console.WriteLine(SetWinEventHook(1, 0x7fffffff, IntPtr.Zero, listener, processId, threadId, SetWinEventHookFlags.WINEVENT_INCONTEXT).ToString());
Console.WriteLine("done");
Console.ReadKey();
}
private static void EventCallback(IntPtr hWinEventHook, int iEvent, IntPtr hWnd, int idObject, int idChild, int dwEventThread, int dwmsEventTime)
{
//callback function, called when message is intercepted
Console.WriteLine(hWnd.ToString());
}
}
}
据我所知,我使用的是正确的P/Invoke的声明,但是当我运行这段代码的输出是:
0 done
如果成功的话,它应该返回一个HWINEVENTHOOK值标识此事件挂接实例。如果不成功,它返回0.(根据微软的网站至少) 线程和进程似乎是有效的和运行。
任何人都可以帮助我更接近我的问题是什么?我认为它一定要么是小事,要么我只是用完全错误的方法去做我想做的事情。提前致谢。
我发现部分问题,应该是使用SetWinEventHookFlags.WINEVENT_OUTOFCONTEXT代替SetWinEventHookFlags.WINEVENT_INCONTEXT。否则它期望我提供一个dll,它可以在其中找到“上下文” – NoCode 2012-08-04 19:38:54
,但仍然没有窗口消息被捕获 – NoCode 2012-08-04 19:39:15