C# 使用 ManagementEventWatcher 監聽 Win32_Process 建立事件,需移植至 VC++ 實現相同功能。
Windows Management Instrumentation (WMI) 提供 COM 介面,C++ 可透過 IWbemLocator、IWbemServices、IWbemObjectSink 訂閱事件。
CoInitializeEx、CoInitializeSecurity。IWbemLocator 並連線 ROOT\\CIMV2 命名空間。IWbemObjectSink 接收事件(Indicate 方法)。ExecNotificationQueryAsync 訂閱 WQL 查詢:SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_Process'Indicate 中解析 TargetInstance 取得 Name、ProcessId 等屬性。#define _WIN32_DCOM
#include
#include
#include
#include
#pragma comment(lib, "wbemuuid.lib")
class ProcessCreateSink : public IWbemObjectSink {
// 實作 AddRef, Release, QueryInterface, Indicate, SetStatus
// Indicate 內解析 IWbemClassObject 取得 Name
};
int main() {
// 1. COM 初始化
// 2. 連線 WMI
// 3. 設定安全性
// 4. 建立 UnsecuredApartment 取得 Stub Sink
// 5. ExecNotificationQueryAsync 訂閱事件
// 6. 訊息迴圈保持執行緒存活
// 7. 清理資源
}
CreateToolhelp32Snapshot 比對進程列表,簡單但有延遲。WMI 事件訂閱是最標準、無侵入式的進程監控方式,C++ 雖較 C# 繁瑣,但可完全掌控生命週期與效能。