Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win


SetWindowsHookEx() fails inside a thread of Windows service created using AfxBeginThread()

Posted on 2004-04-28
Medium Priority
Last Modified: 2013-12-03
I’ve written a piece of code that works perfectly fine inside an executable on Win 2k platform, but does not work when invoked from a multi threaded Windows Service.

The task is to track change in value of a status bar and items of a list control on a 3rd party executable. The window for this target application is first searched using EnumWindows() and than the following code is executed

g_hinstDll = LoadLibrary("hookDLL.dll");

if (g_hinstDll == NULL) {
// Set WH_CALLWNDPROCRET hook on the 3rd party application thread            
g_hhook = ::SetWindowsHookEx(WH_CALLWNDPROCRET, (HOOKPROC)CallWndProcRet, g_hinstDll, m_target_threadid);

if (g_hhook == NULL) {
TRACE("Can't create hook! Error Code = %d\n",GetLastError());

This code works perfectly when compiled as an executable. But if we run this code in a thread invoked using AfxBeginThread(), inside a Windows Service, it fails with the error code ERROR_ACCESS_DENIED after the SetWindowsHookEx call.

Q - Can somebody give some pointers on what could be the reason for the error message?

Additional Information –
•      The service has the option ‘Allow service to interact with the desktop’ option selected, to facilitate search of the target application window thread.

•      Currently logged on user is part of the Administrators group.

•      Inside this particular thread in the service, i’m able to open the target process using these calls
OpenProcess(STANDARD_RIGHTS_REQUIRED, FALSE, m_target_processid)

•      Call for starting the thread is
Question by:__Sarge
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
  • 2
LVL 86

Accepted Solution

jkr earned 372 total points
ID: 10938893
>>but does not work when invoked from a multi threaded Windows Service.

What kind of messages of would you like to hook on an invisible desktop that has no windows? See http://www.microsoft.com/msj/0398/service2.aspx ("Why Do Certain Win32 Technologies Misbehave in Windows NT Services?"):

On Windows NT 4.0, only one window station can be visible, WinSta0. The visible window station is also defined as interactive. A nonvisible window station is noninteractive. A nonvisible window station does not receive any user input and no display device is associated with it.
As stated earlier, desktops are contained within window station objects, just as a directory contains files. A desktop object contains a logical display surface and includes windows, menus, and hooks. Only desktops belonging to the visible window station can be seen and receive user input and only one desktop can be seen and receive input at a time. This desktop is known as the active desktop.

Author Comment

ID: 10957041
Thanks for your comment. The article is very informative.

The application that has to be hooked is on the interactive desktop. The service thread that is trying to hook this interactive desktop application, is running under LocalSystem account, with 'Allow service to interact desktop' option selected. This allows the service thread access to the interactive desktop.

The service thread has following piece of code

g_hinstDll = LoadLibrary("hookDLL.dll");

g_hhook = ::SetWindowsHookEx(WH_CALLWNDPROCRET, (HOOKPROC)CallWndProcRet, g_hinstDll, m_target_threadid);

SetWindowsHookEx() fails with  ERROR_ACCESS_DENIED.

Could it be related to g_hinstDll handle? This module of this handle is under LocalSystem context. Is this creating a problem?

Any other idea on what could be reason for this error?

LVL 86

Expert Comment

ID: 10962381
>>Could it be related to g_hinstDll handle?

No. It is related to the fact that you cannot hook anything from a service running on an invisible desktop.
Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.


Expert Comment

ID: 11013848
>No. It is related to the fact that you cannot hook anything from a service running on an invisible desktop.

Isn't it more accurate to say: You cannot hook anything in a thread that belongs to a desktop other than the current one?  

I imagine the ERROR_ACCESS_DENIED relates to the attempt to cross this desktop boundary.  However, threads running within the scope of the service will be receiving messages (just not WM_PAINTs), and I think these could be hooked if desired.  (Though that's not what Sarge is trying to do.)

'Allow service to interact desktop' does not get around the above restriction. If you need the main part of your program to run as a service, I think you will have to factor out the part that establishes the hook into a separate process. The service could create this on the interactive desktop and perhaps communicate with it via a named pipe, if necessary.


Expert Comment

ID: 11015881
Hi Sarge,

Well, I may have been wrong.  My apologies.  

I thought that "interactive services" still ran in a separate Window Station and desktop, and yet somehow were allowed to interact with the user.  Having looked for more information via Google, it sounds like they actually run in the interactive Window Station/desktop.  I can't find an explicit statement of this, but it's implied by various things I've seen.

I found this MS KB article relating to NT4 -

So, unless Win2k has been deliberately changed to prevent this, it sounds like what you are trying ought to work.  Although, MS actually recommend the approach I mentioned above, for security reasons  -



Expert Comment

ID: 11016068

Author Comment

ID: 11037293
Thanks for all your inputs.

I have already tried launching a new process(Win32 exe) through CreateProcess() in the interactive desktop. I could see the GUI of the launched exe, but even this exe could not hook the target application. The error returned was the same  ERROR_ACCESS_DENIED.

I cannot use CreateProcessWithLogonW() as the service also needs to run on WinNT4.0. I would see if CreateProcessAsUser(), works in this case.


Assisted Solution

colmcc earned 368 total points
ID: 11040054
Hi Sarge,

Yes.  CreateProcess would still give ERROR_ACCCESS_DENIED because the user would still be LocalSystem. (Assuming that the problem is the one described in the MS KB article.)

CreateProcessAsUser sounds like a good idea.  You would need to get hold of an access token for the logged-on user, which can be a bit tricky I think.  Possibly OpenProcessToken on the hook-target process, followed by ImpersonateLoggedOnUser might do the trick.

But it is still a bit worrying that the MS KB article suggests that the problem you are seeing with the service was fixed in NT4 SP2.  Maybe there is something else going on here?

A few things you could try :

Run the service on NT4 (SP >= 2).  Do you get the same error?

Replace AfxBeginThread with the Win32 function CreateThread. (It seems unlikely, but maybe MFC is screwing things up somehow.)

If the problem really is that LocalSystem has no access to the user's desktop, perhaps it would be possible to allow this access (DF_ALLOWOTHERACCOUNTHOOK), using SetUserObjectInformation.

None of the above is particularly well thought through, but maybe it will give you a few ideas.

Good luck,

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows a few slightly more advanced techniques for Windows 7 gadget programming, including how to save and restore user settings for your gadget and how to populate the "details" panel that is displayed in the Windows 7 gadget gallery.  …
Entering time in Microsoft Access can be difficult. An input mask often bothers users more than helping them and won't catch all typing errors. This article shows how to create a textbox for 24-hour time input with full validation politely catching …
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question