Click here to Skip to main content
15,882,209 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
I am creating a window service application in which I have to findout out which is current active window(which have keyboard focus).I have done like this but this is returning null values always.

        static extern IntPtr GetForegroundWindow();

const int nChars = 256;
            IntPtr handle = IntPtr.Zero;
            StringBuilder Buff = new StringBuilder(nChars);
            handle = GetForegroundWindow();
            if (GetWindowText(handle, Buff, nChars) > 0)
                return Buff.ToString();
            Log.WriteLine("Returning  Null");
            return null;

But I have tried Same logic in console application but its working fine in that.Is there any other way to findout out active window in window service?
Kindly help me out.

Updated 13-Apr-11 22:00pm

1 solution

From Vista onwards, services cannot interact with the UI. So calls like GetForegroundWindow will not work. This is by design.

The workaround is to have a stub client application that calls GetForegroundWindow and communicates with the service. For any UI function, the service proxies through the stub client.
Share this answer
manushi88 13-Apr-11 13:50pm    
Hi Nishant,
Thanks for helping.I am new to window service.Can you please help me out with the concept of stub client.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900