【发布时间】:2014-02-27 11:47:02
【问题描述】:
是否最好使用相同的 WinEventProc() 回调函数注册多个 SetWinEventHook() 函数,并在函数代码中单独处理每个事件类型,或者尽可能多地处理。
编辑:我发布了三个不同的场景,我想知道哪个是最好的,为什么?
案例 1:单个回调、单个委托、多个钩子
static WinEventDelegate SingleCallbackDelegate = new WinEventDelegate(SingleCallback);
public static void SingleCallback(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
switch(evenType) :
case eventId1 : // do work related to event 1
case eventId2 : // do work related to event 2
// etc.
}
void SetHooks()
{
SetWinEventHook(eventId1, eventId1, IntPtr.Zero, SingleCallbackDelegate, 0,
0, flags);
SetWinEventHook(eventId2, eventId2, IntPtr.Zero, SingleCallbackDelegate, 0,
0, flags);
}
案例 2:单个回调、多个委托、多个钩子
static WinEventDelegate CallbackDelegate1 = new WinEventDelegate(SingleCallback);
static WinEventDelegate CallbackDelegate2 = new WinEventDelegate(SingleCallback);
public static void SingleCallback(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
switch(evenType) :
case eventId1 : // do work related to event 1
case eventId2 : // do work related to event 2
// etc.
}
void SetHooks()
{
SetWinEventHook(eventId1, eventId1, IntPtr.Zero, CallbackDelegate1, 0,
0, flags);
SetWinEventHook(eventId2, eventId2, IntPtr.Zero, CallbackDelegate2, 0,
0, flags);
}
案例 3:多个回调、多个委托、多个钩子
static WinEventDelegate CallbackDelegate1 = new WinEventDelegate(Callback1);
public static void Callback1(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
// do work related to event 1
}
static WinEventDelegate CallbackDelegate2 = new WinEventDelegate(Callback2);
public static void Callback1(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
// do work related to event 2
}
void SetHooks()
{
SetWinEventHook(eventId1, eventId1, IntPtr.Zero, CallbackDelegate1, 0,
0, flags);
SetWinEventHook(eventId2, eventId2, IntPtr.Zero, CallbackDelegate2, 0,
0, flags);
}
【问题讨论】:
-
@HansPassant 我设法使用相同的回调为不同的事件(EVENT_SYSTEM_FOREGROUND 和 EVENT_OBJECT_NAMECHANGE)注册了钩子。
-
@HansPassant 检查我上次的编辑。
-
@DavidHeffernan 你也可以看看这个吗?
标签: c# .net windows event-handling ui-automation