C#获取系统服务+进程+启动时间

原文: C#获取系统服务+进程+启动时间

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38208401/article/details/77592653

1、起因

起因:我们wpf程序进程wisptis.exe(在系统和输入设备之间通信)先于系统服务TabletInputService(加载支持触控手写功能)启动,导致系统文件列表无法滑动
方案:开机启动后,收集系统服务和进程和各自的启动时间

2、服务

1)services.msc查看服务,并无启动时间,找了很久,发现windows系统日志存在服务的启动时间记录(清空日志,重启计算机即可)
这里写图片描述
2)开始代码获取服务+启动时间:(需要引用系统程序集:System.ServiceProcess)

string[] logTypes = new string[] { "System" };//"Application"应用程序, "Security"安全, "System"系统
foreach (string t in logTypes)
{
    EventLog eSystem = new EventLog();
    eSystem.Log = t;
    string systeminfo = "";
    foreach (EventLogEntry log in eSystem.Entries)
    {
        if (log.Message.Contains("服务处于 正在运行 状态") && log.ReplacementStrings.Any())//由于获取的并不全是服务,所以加个包含的判断
        {
            systeminfo = systeminfo + "\r\n" + log.ReplacementStrings.First() + "-----" + log.TimeGenerated + "\r\n";//Message其实是ReplacementStrings两个值拼接的,这里我只要服务所以只取了第一个
        }
        txt_systeminfo.Text = systeminfo;
    }
}

执行效果:
这里写图片描述

3、进程

1)msinfo32查看进程
这里写图片描述
2)获取进程和启动时间

Process[] myProcesses;
myProcesses = Process.GetProcesses();
string processinfo = "";
foreach (Process p in myProcesses)
{
   processinfo = processinfo + "\r\n" + p.ProcessName + "-----" + p.StartTime + "\r\n";
}
txt_processinfo.Text = processinfo;

直接获取进程的开始时间,一直Win32Exception异常拒绝访问
这里写图片描述
原因是权限不够,找了段也没太明白的代码解决了此问题(需要引用系统程序集:System.Management)

private DateTime GetProcessStartTimeById(int processId)
{
   String queryString = "select CreationDate from Win32_Process where ProcessId='" + processId + "'";
   SelectQuery query = new SelectQuery(queryString);

   ManagementScope scope = new ManagementScope(@"\\.\root\CIMV2");
   ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
   ManagementObjectCollection processes = searcher.Get();

   DateTime startTime = DateTime.Now;
   foreach (var process in processes)
   {
      startTime = ManagementDateTimeConverter.ToDateTime(process["CreationDate"].ToString());
      break;
    }
   return startTime;
}

将p.StartTime替换成GetProcessStartTimeById(p.Id)即可,执行效果:
这里写图片描述

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/11254695.html