Aerik
Aerik

Reputation: 2317

How do I get the foreground window from a windows service?

I'm using some code like this Get active window text (and send more text to it) to send keys to the foreground window. When I run it from the console, it works great. When I run it from my service, the GetForegroundWindow() call returns 0 (zero). How can I get the foreground window handle from my service?

EDIT: A little research tells me about services running as different sessions - if that is relevant to my problem, I need to know how to get the foreground window of the console (physical monitor) session if one exists.

EDIT #2: My use case only involves XP.

Upvotes: 0

Views: 2707

Answers (1)

Antonio Bakula
Antonio Bakula

Reputation: 20693

Well on XP GetForegroundWindow will work if you set

Allow service to interact with desktop

check box in service properties (Log on tab). This is NOT working on Vista and newer.

But you shouldn't do that, in fact you shouldn't call GetForegroundWindow from service, services run even when there are no users logged, and they also work when there is a more than one user logged on.

I don't know why you are doing this from windows service, but maybe simple desktop app hidden in tray will do the trick.

Upvotes: 1

Related Questions