SetWinEventHook callback does not work when app is a service

て烟熏妆下的殇ゞ 提交于 2019-12-11 08:10:00

问题


I have an app made in .NET 4.0 that hooks on win events and uses a callback to catch the window events like so:

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

This code works perfectly when the app is configured as a console app. But I want it to run as a service, so I change a bit the loop because we cannot have a continuous loop in OnStart method of the service. So I made a timer that reads messages at a 50 ms interval like so:

MSG msg;
        if (PeekMessage(out msg, IntPtr.Zero, 0, 0, PM_REMOVE))
        {
            TranslateMessage(ref msg);
            DispatchMessage(ref msg);
        }
//

I also changed the entire app, I created a new project as a window Service created a installer for the service and made it run. It runs ok as a service but I don't get events notifications. My assumption is that there is some issues with the windows rights when running an app as a service.
The app is made on Win7 64 with Visual Studio 2010 .NET 4.0
Do you have any idea on why I don't catch the event notifications?
Thank you

来源:https://stackoverflow.com/questions/25638164/setwineventhook-callback-does-not-work-when-app-is-a-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!