我需要模拟用户在WebBrowser文本字段中键入的内容(没有被检测为机器人)。所有相应的javascript事件均应引发。如果仅发送import Affiliates from './affiliates.json'
Affiliates.map((p)=> {
console.log(p.id)
}
,则不会引发按键下降/按键上升事件。但是当我发送WM_CHAR
,WM_KEYDOWN
,WM_CHAR
时,字符被写入3次。如果我仅发送WM_KEYUP
,则不会引发按键事件(但是即使没有WM_KEYDOWN
,也会引发按键事件)。如果仅发送WM_CHAR
,则不会引发键上移/下移事件。在英语键盘处于活动状态时,如果不使用WM_KEYUP
也不发送西里尔字符,将不起作用。那么如何正确地做一次只写一个字符并引发所有这些事件呢?
WM_CHAR
似乎正常的键入导致lParam的值类似于 [DllImport("User32.dll", CharSet = CharSet.Unicode)]
static extern int PostMessage(IntPtr hWnd, int uMsg, IntPtr wParam, IntPtr lParam);
[DllImport("User32.dll", CharSet = CharSet.Unicode)]
static extern int PostMessage(IntPtr hWnd, int uMsg, int wParam, IntPtr lParam);
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
public const Int32 WM_CHAR = 0x0102;
public const Int32 WM_KEYDOWN = 0x0100;
public const Int32 WM_KEYUP = 0x0101;
void SendCharacter(char character, IntPtr hWnd)
{
var key = new IntPtr(character);
var scanKey = new IntPtr((int)ConvertCharToVirtualKey(character));
PostMessage(hWnd, WM_KEYDOWN, scanKey , IntPtr.Zero);
PostMessage(hWnd, WM_CHAR, key, IntPtr.Zero);
PostMessage(hWnd, WM_KEYUP, scanKey , IntPtr.Zero);
}
public static Keys ConvertCharToVirtualKey(char ch) {
short vkey = VkKeyScan(ch);
Keys retval = (Keys)(vkey & 0xff);
int modifiers = vkey >> 8;
if ((modifiers & 1) != 0) retval |= Keys.Shift;
if ((modifiers & 2) != 0) retval |= Keys.Control;
if ((modifiers & 4) != 0) retval |= Keys.Alt;
return retval;
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern short VkKeyScan(char ch);
的1966081和WM_KEYDOWN
的值为3221191553,但是每次运行应用程序时它们都有些不同。粘贴这些值会导致3个重复字符之一消失。
更新
工作版本:
WM_CHAR
根据MSDN,WM_KEYUP
的{{1}}位应该为0,但是如果我没有将其设置为1,它会重复多次字符。仍在等待答案如何正确完成