简体   繁体   English

如何使用C#Windows Service获取正在运行的应用程序

[英]How to Get Running Application with C# Windows Service

I've build a Windows service with C# which get all running applications on my computer (Notepad,...). 我已经使用C#构建了Windows服务,该服务可以在计算机上运行所有正在运行的应用程序(记事本等)。 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);
    }
  }
}

That's why you are checking MainWindowTitle on your code. 这就是为什么要在代码上检查MainWindowTitle的原因。 You have to know MainWindowTitle has value just for those processes which they have GUI like notepad or skype or ... 您必须知道MainWindowTitle仅对于它们具有GUI的进程(如记事本,Skype或...)具有价值。

To identify all the process name it's better to check ProcessName property to get the process name. 要标识所有进程名称,最好检查ProcessName属性以获取进程名称。

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));
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM