1

I've build a Windows service with C# which get all running applications on my computer (Notepad,...). I've tryed this following code but it doesn't work :

Thank you all for your help!

Process[] processes = Process.GetProcesses();
using (TextWriter tw = new StreamWriter(@"C:\Users\Public\Documents\Info.txt"))
{
  foreach(Process p in processes)
  {
    if(!String.IsNullOrEmpty(p.MainWindowTitle))
    {
      tw.WriteLine(p.MainWindowTitle);
    }
  }
}
Paul Adam
  • 251
  • 1
  • 2
  • 11
Lama
  • 15
  • 4
  • Can you specify what (and in what way) is not working? – Jimi Jan 08 '19 at 07:29
  • 1
    Thank you for replying! It shows nothing. I think, may be the Windows Service can't interact with "MainWindowTitle". Because i've tryed this code with Windows form and it works. – Lama Jan 08 '19 at 07:48
  • 1
    [Getting window titles from a windows service](https://stackoverflow.com/a/24294244/7444103). [ServiceController.GetServices](https://learn.microsoft.com/en-us/dotnet/api/system.serviceprocess.servicecontroller.getservices). – Jimi Jan 08 '19 at 07:55

1 Answers1

0

That's why you are checking MainWindowTitle on your code. You have to know MainWindowTitle has value just for those processes which they have GUI like notepad or skype or ...

To identify all the process name it's better to check ProcessName property to get the process name.

So I recommend you to change your code like this:

using (TextWriter tw = new StreamWriter(@"C:\Users\Public\Documents\Info.txt"))
{
    foreach (Process p in processes)
    {
        if (!String.IsNullOrEmpty(p.ProcessName))
        {
            var processTitle= !string.IsNullOrEmpty(p.MainWindowTitle) ? p.MainWindowTitle: "N/A";
            tw.WriteLine(string.Format("Process Name: {0} \t\t Process GUI Title:{1}",p.ProcessName, processTitle));
        }
    }
}
Mohammad Nikravesh
  • 947
  • 1
  • 8
  • 27