3

可能重复:
跟踪 Windows 中启动的应用程序

我喜欢在 C# 中创建一个程序或服务,用于监控用户何时启动某个应用程序,如 excel 或 access。使用 System.Diagnostics.Process 我可以获得正在运行的进程,但我想在用户启动应用程序时监视事件。我们想创建某种使用历史。

4

3 回答 3

4

您可以使用 WMI 来做到这一点:

private ManagementEventWatcher WatchForProcessStart(string processName)
{
    string queryString =
        "SELECT TargetInstance" +
        "  FROM __InstanceCreationEvent " +
        "WITHIN  10 " +
        " WHERE TargetInstance ISA 'Win32_Process' " +
        "   AND TargetInstance.Name = '" + processName + "'";

    // The dot in the scope means use the current machine
    string scope = @"\\.\root\CIMV2";

    // Create a watcher and listen for events
    ManagementEventWatcher watcher = new ManagementEventWatcher(scope, queryString);
    watcher.EventArrived += ProcessStarted;
    watcher.Start();
    return watcher;
}

private void ProcessStarted(object sender, EventArrivedEventArgs e)
{
    ManagementBaseObject targetInstance = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value;
    string processName = targetInstance.Properties["Name"].Value.ToString();
    Console.WriteLine(String.Format("{0} process started", processName));
}

它监视 10 个最新进程的数组,并在事件发生变化时调用事件

于 2012-09-10T09:52:55.873 回答
4

我做了一个小例子,使用WqlEventQuery对象来检查是否有一个新的进程实例。然后检查名称并按照您的意愿进行操作。如果您想改进我的查询,请随意查看相应的语法说明

private static void lookForExcel()
{
    WqlEventQuery query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0, 0, 1), "TargetInstance isa \"Win32_Process\"");
    ManagementEventWatcher watcher = new ManagementEventWatcher(query);
    watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
    watcher.Start();
    Console.ReadLine();
    watcher.Stop();
}

static void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
    string instanceName = ((ManagementBaseObject)e.NewEvent["TargetInstance"])["Name"].ToString();
    if (instanceName.ToLower()=="excel.exe")
    {
        Debug.WriteLine("Excel has been started ...");    
    }            
}
于 2012-09-10T10:03:04.953 回答
0

最简单的方法是定期检查正在运行的进程,并与之前的列表进行比较。

但是,您可以在进程开始时收到通知。此处的文档:

您还可以在安全事件日志中打开“详细跟踪”,然后它将显示系统上启动和结束的每个进程。不过那可能太多了。

于 2012-09-10T09:52:48.547 回答