Getting window titles in the service

Jun 5 2010 8:37 AM
First, I want to apologize, that I´m asking about quite freqently discused topic, but I was searching two days on the internet and I didn´t find anything, what would solve my problem.

I´m programming windows service, which would collect info about all started windows (concretly window titles). I was trying to pass it via this code (I have it on thread):
while (true)
{
Thread.Sleep(1000); //Because of high CPU.
foreach
(Process currentProcess in Process.GetProcesses())
{
if (currentProcess.MainWindowTitle.Contains("Something"))
{
//Window has been found.
}
}
}
Normally (in console app.) it works perfectly. But when I put it into my win service, nothing happen. So I got a list (saved to the text file, by the same way like in the code up) of all "MainWindowHandle"s and started it like a service. All values were on zero. Then I tried API as well:
//Dll imports:
[DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Ansi)]
private static extern IntPtr FindWindow(string className, string windowName);
[DllImport("user32.dll", EntryPoint = "GetWindowText", CharSet = CharSet.Ansi)]
private static extern bool GetWindowText(IntPtr hWnd, [OutAttribute()] StringBuilder strNewWindowName, Int32 maxCharCount);
//And then:
while (true)
{
Thread.Sleep(1000); //Because of high CPU.
FileStream stream = new FileStream(@"some path\info.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(stream);
StringBuilder sbWinText = new StringBuilder(256);
GetWindowText(FindWindow(null, "Some text in title"), sbWinText, 256);
writer.WriteLine(sbWinText.ToString());
writer.Close();
}
The txt was empty and when I tried to get the handle (by "FindWindow"), I got zero again. It looks, that  my servis doesn´t see the main window of the processes at all.

Does anybody know how to solve it?

Thanks for replies.


Answers (6)