UPD。我在C ++ win32代码中有相同的情况。
C#:
WinAPI部分:
const uint EVENT_CONSOLE_CARET = 0x4001;
const uint EVENT_CONSOLE_END_APPLICATION = 0x4007;
delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType,
IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
[DllImport("user32.dll", SetLastError = true))]
static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax,
IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc,
uint idProcess, uint idThread, uint dwFlags);
[DllImport("user32.dll")]
static extern bool UnhookWinEvent(IntPtr hWinEventHook);
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
代码:
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.Start();
_winEventProc = new WinEventDelegate(WinEventProc);
m_hhook = SetWinEventHook(EVENT_CONSOLE_CARET,
EVENT_CONSOLE_END_APPLICATION,
IntPtr.Zero,
_winEventProc,
(uint) process.Id,
0,
WINEVENT_OUTOFCONTEXT);
lastError = Marshal.GetLastWin32Error();
我的程序无法捕获我创建的进程中的事件。如果我将“(uint)process.Id”更改为“(uint)0”它运行良好。我将“(uint)process.Id”更改为特定进程Id(在任务管理器中观察)并且结果相同(不良)。我甚至尝试过:
1)启动cmd.exe(*)
2)启动我的程序而不创建新的cmd.exe进程
3)按cmd.exe(*)
上的任意键4)在_winEventProc中使用GetWindowThreadProcessId
5)用pID重新运行我的程序4步
它不起作用。我不知道为什么,但它只适用于processID 0。
P.S。抱歉我的英文不好