我目前正在致力于自动化无法更改的 Win32 UI 应用程序。到目前为止,我的方法是使用目标应用程序的标准消息队列来注入(inject)我的输入。我已经深入了解了:
- 使用
WM_COMMAND
可以“点击”按钮 - 通过
TCM_GETITEMA
读取选项卡名称并通过虚拟鼠标点击激活它们WM_LBUTTONDOWN
/WM_LBUTTONUP
有效 - 读取控件的启用/禁用状态有效
但是,我遇到困难的地方是修改可编辑组合框及其编辑控件的文本。我尝试像这样使用 WM_SETTEXT
消息:
public static void SetText(IntPtr hWnd, string text) {
// Maximum item text buffer length
const int MAX_LEN = 512;
// Get process
uint ProcessId;
WinAPI.GetWindowThreadProcessId(hWnd, out ProcessId);
IntPtr process = WinAPI.OpenProcess(
WinAPI.ProcessAccessFlags.VMOperation | WinAPI.ProcessAccessFlags.VMRead |
WinAPI.ProcessAccessFlags.VMWrite | WinAPI.ProcessAccessFlags.QueryInformation,
false, ProcessId
);
if( process == IntPtr.Zero )
throw new Exception("Could not open process");
// Allocate memory in remote process
IntPtr farTextPtr = WinAPI.VirtualAllocEx(process, IntPtr.Zero, MAX_LEN,
WinAPI.AllocationType.Commit,
WinAPI.MemoryProtection.ReadWrite
);
try {
if( farTextPtr == IntPtr.Zero )
throw new Exception("Could not allocate memory in target process");
IntPtr nearTextPtr, pData;
int bytesRead;
// Write item text to remote memory (Unicode!)
nearTextPtr = Marshal.StringToHGlobalUni(text);
WinAPI.WriteProcessMemory(process, farTextPtr, nearTextPtr, MAX_LEN, out bytesRead);
Marshal.FreeHGlobal(nearTextPtr);
// Just for debugging purposes, read it back to verify it was set properly
pData = Marshal.AllocHGlobal(MAX_LEN);
WinAPI.ReadProcessMemory(process, farTextPtr, pData, MAX_LEN, out bytesRead);
text = Marshal.PtrToStringUni(pData);
Marshal.FreeHGlobal(pData);
// Set the text
int res = WinAPI.SendMessage(hWnd, Constants.WM_SETTEXT, IntPtr.Zero, farTextPtr);
if( res != 1 ) throw new Exception("SendMessage WM_SETTEXT failed");
} finally {
// Free remotely allocated memory
if( farTextPtr != IntPtr.Zero )
WinAPI.VirtualFreeEx(process, farTextPtr, 0, WinAPI.FreeType.Release);
WinAPI.CloseHandle(process);
}
}
这行不通!如果我将 Spy++ 附加到目标控件,我可以看到,消息已收到,但接收到的 wParam
与我在调用 SendMessage
时指定的不同。
例如对 VirtualAllocEx
的调用在目标进程中返回了一个指针,值为 0x048b0000
。在 Spy++ 中收到的消息中,我看到值 0x0011AA88
是错误的:
<000009> 0004065E S WM_SETTEXT lpsz:0011AA88 ("<random characters here>") [wParam:00000000 lParam:0011AA88]
指针是否以某种方式被改变了?我在我的例程中执行相同的过程以从控件中检索字符串,就像使用 TabControl 一样。它在那里完美地工作。使用 WM_SETTEXT
时有什么不同吗?
最佳答案
是的,WM_SETTEXT
是标准的 Windows 消息,操作系统将负责将数据复制到目标进程。您必须传递一个在您自己的进程中有效的指针。
关于c# - SendMessage WM_SETTEXT 到另一个进程失败,因为目标进程中接收到的指针已更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48590915/