我有一个在 .NET 4.0 中制作的应用程序,它挂钩 win 事件并使用回调来捕获窗口事件,如下所示:
//import the methos from the dll
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetWinEventHook(int eventMin, int eventMax, IntPtr hmodWinEventProc, WinEventProc lpfnWinEventProc, int idProcess, int idThread, int dwflags);
//declare a callback
public static WinEventProc _winEventProc = new WinEventProc(WindowEventCallback);
//pass this callback to SetWinEventHook
SetWinEventHook(
EVENT_SYSTEM_FOREGROUND, // eventMin
EVENT_SYSTEM_FOREGROUND, // eventMax
IntPtr.Zero, // hmodWinEventProc
_winEventProc,
0, // idProcess
0, // idThread
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS);
//define somthing in callback
private static void WindowEventCallback(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
Logger.Instance.Write("WindowEventCallback");
}
//the loop that reads the messages
while (true)
{
if (PeekMessage(out msg, IntPtr.Zero, 0, 0, PM_REMOVE))
{
if (msg.Message == WM_QUIT)
break;
TranslateMessage(ref msg);
DispatchMessage(ref msg);
}
}
当应用程序配置为控制台应用程序时,此代码可以完美运行。
但我希望它作为服务运行,所以我对循环做了一些更改,因为我们不能在服务的 OnStart 方法中进行连续循环。所以我制作了一个计时器,以 50 毫秒的间隔读取消息,如下所示:
MSG msg;
if (PeekMessage(out msg, IntPtr.Zero, 0, 0, PM_REMOVE))
{
TranslateMessage(ref msg);
DispatchMessage(ref msg);
}
//
我还更改了整个应用程序,我创建了一个新项目作为窗口服务,为该服务创建了一个安装程序并使其运行。它作为服务运行正常,但我没有收到事件通知。
我的假设是,将应用程序作为服务运行时,Windows 权限存在一些问题。
该应用程序是在 Win7 64 上使用 Visual Studio 2010 .NET 4.0 制作的
您知道为什么我收不到事件通知吗?
谢谢