如何监视应用程序是否已打开
本文关键字:是否 应用程序 何监视 监视 | 更新日期: 2023-09-27 18:35:21
我正在实施一个桌面分析应用程序,该应用程序需要记录用户在PC上打开的程序的名称和时间。 它是一个 C# (WPF) 应用程序,在用户登录时启动,并在没有 UI 的情况下运行。 对于Word或IE等程序,它还将捕获他们正在查看的文档或URL。
目前我有一个工作解决方案如下:
安装一个用于鼠标按下的窗口挂钩。 当该事件触发时,我使用 p-Invoke 来"GetForegroundWindow",然后使用窗口句柄来"GetWindowThreadProcessId",使用 ProcessId,我可以获取包含名称、开始时间和参数开始列表的 System.Diagnostics.Process 对象。 我维护一个历史记录列表,因此只有在以前未记录此 processId/窗口句柄组合的情况下,我才会编写跟踪条目。
此解决方案确实可以正常工作,但需要鼠标钩子,它可以在没有任何通知或无法有问题地检查它是否仍然挂上的情况下被 Windows 丢弃。 更不用说这个实现似乎是一个黑客。
如果有更好更直接的方法,请告知。
谢谢。
__InstanceCreationEvent
事件和 Win32_Process
WMI 类来监视创建的进程。
试用此示例 C# 应用程序
using System;
using System.Collections.Generic;
using System.Management;
using System.Text;
namespace GetWMI_Info
{
public class EventWatcherAsync
{
private void WmiEventHandler(object sender, EventArrivedEventArgs e)
{
//in this point the new events arrives
//you can access to any property of the Win32_Process class
Console.WriteLine("TargetInstance.Handle : " + ((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["Handle"]);
Console.WriteLine("TargetInstance.Name : " + ((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["Name"]);
}
public EventWatcherAsync()
{
try
{
string ComputerName = "localhost";
string WmiQuery;
ManagementEventWatcher Watcher;
ManagementScope Scope;
Scope = new ManagementScope(String.Format("''''{0}''root''CIMV2", ComputerName), null);
Scope.Connect();
WmiQuery ="Select * From __InstanceCreationEvent Within 1 "+
"Where TargetInstance ISA 'Win32_Process' ";
Watcher = new ManagementEventWatcher(Scope, new EventQuery(WmiQuery));
Watcher.EventArrived += new EventArrivedEventHandler(this.WmiEventHandler);
Watcher.Start();
Console.Read();
Watcher.Stop();
}
catch (Exception e)
{
Console.WriteLine("Exception {0} Trace {1}", e.Message, e.StackTrace);
}
}
public static void Main(string[] args)
{
Console.WriteLine("Listening process creation, Press Enter to exit");
EventWatcherAsync eventWatcher = new EventWatcherAsync();
Console.Read();
}
}
}
如果你想监视Windows上运行的所有内容的性能,那么PerformanceCounter类就是这样。每次应用程序启动 Windows 时,都会创建数十个性能计数器来跟踪应用程序的 ProcessID、CPU 使用率、内存使用率、每秒 I/O 操作数等。
例如,以下代码将为您提供 Chrome 的进程 ID:
PerformanceCounter perf = new PerformanceCounter("Process", "ID Process", "chrome");
int procId = (int)perf.NextValue();
您还可以使用 PerformanceCounterCategory 类轻松枚举类别、实例和计数器。
您可以使用Windows的PerfMon工具来了解您将能够检索哪些信息。我建议您查看进程类别(使用 PerfMon),您将在其中找到所有活动进程的列表。