WM_CHAR 不适用于 notepad.exe

WM_CHAR doesn't work with notepad.exe

我使用 Windows 7 和 Microsoft Visual Studio 2010。我使用此代码将数字字符插入到 calc.exe 的 window:

STARTUPINFO         si  = { 0 };
PROCESS_INFORMATION pi  = { 0 };

memset(&si, 0, sizeof(si));
memset(&pi, 0, sizeof(pi));

si.cb = sizeof(si);

BOOL bResult = CreateProcess("c:\windows\syswow64\calc.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
WaitForInputIdle(pi.hProcess, INFINITE);
HWND hWnd = FindWindow("CalcFrame", NULL);

PostMessage(hWnd, WM_CHAR, (WPARAM)'1', 0);
PostMessage(hWnd, WM_CHAR, (WPARAM)'2', 0);
PostMessage(hWnd, WM_CHAR, (WPARAM)'3', 0);
PostMessage(hWnd, WM_CHAR, (WPARAM)'4', 0);

这段代码完美无缺。当我将 "c:\windows\syswow64\calc.exe" 替换为 "c:\windows\syswow64\notepad.exe" 并将 "CalcFrame" 替换为 "Notepad" 时,它不会将字符插入记事本 window.

记事本的主 window 的客户区内有 class EDIT 的子 window。对于您正在做的事情,您需要找到并将消息发送到 that window 而不是记事本的主要 window.

BOOL bResult = CreateProcess("c:\windows\syswow64\notepad.exe", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);
WaitForInputIdle(pi.hProcess, INFINITE);
HWND hWnd = FindWindow("Notepad", NULL);
hWnd = FindWindowEx(hWnd, NULL, "EDIT", NULL); // <-- add this

PostMessage(hWnd, WM_CHAR, (WPARAM)'1', 0);
PostMessage(hWnd, WM_CHAR, (WPARAM)'2', 0);
PostMessage(hWnd, WM_CHAR, (WPARAM)'3', 0);
PostMessage(hWnd, WM_CHAR, (WPARAM)'4', 0);

使用 Spy++ 探索 window 层次结构并找到这些东西。