Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a code part like this in my project :
private void GetActiveWindow()
        {
           
            const int cChars = 256;
            int ihandler = 0;
            StringBuilder sBuff = new StringBuilder(cChars);
            ihandler = GetForegroundWindow();
              StreamWriter sw;
            if (File.Exists("C:\\Log.txt"))
            {
                sw = File.AppendText("C:\\Log.txt");
                sw.WriteLine(sBuff.ToString() + "->" + ihandler.ToString());
                sw.WriteLine("-----------");
                sw.Close();
            }
            else
            {
                sw = new StreamWriter("C:\\Log.txt");
                sw.WriteLine(sBuff.ToString() + "->" + ihandler.ToString());
                sw.WriteLine("-----------");
                sw.Close();
            }
}

It's value always getting 0 and i cant reach active window's name.Iam using Windows 7.And this is a windows service project what should i do ? ihandler always getting 0 so i cant reach name.
Posted
Updated 27-Oct-11 2:59am
v2
Comments
phil.o 27-Oct-11 8:49am    
It's value always getting 0
Which value ?

And can you show us what is the GetForegroundWindow() method ?

I don't think that should ever work when running as a windows service. To start with, services in 7 can't interact with the desktop at all. In addition to that they can run regardless of how many users are logged in, so what should it return if there are multiple users logged in (or none)? Which session should it return the foreground window for?
 
Share this answer
 
Debug your GetForegroundWindow Method.

Here is a information on "How to Debug Windows Service Application".
http://msdn.microsoft.com/en-us/library/7a50syb3%28v=VS.90%29.aspx
 
Share this answer
 
Comments
SercanOzdemir 27-Oct-11 9:02am    
Sorry but Debug can not help me.Need Active window's name so i should learn about windows services and Windows 7. I tried and it works on win forms well.
You can not do what you want. Under Windows 7 all services run under a different Session (session 0) than the user Session (session 1 and above). That means that your service code cannot interact with the users desktop at all. It's no surprise you keep getting 0 returned by GetForegroundWindow. There is no foreground window in Session 0 because there's no UI being displayed.
 
Share this answer
 
Impersonate the logged in user.
 
Share this answer
 
Comments
fjdiewornncalwe 19-Oct-12 15:36pm    
Please don't reopen really old questions like this. The common guideline, although not fixed in stone, is around 5 or 6 monthts. Cheers and welcome to CP.

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