【发布时间】:2018-10-29 10:30:29
【问题描述】:
我在 C# 中对这个项目有一个问题:使用 WinAPI SendInput 函数时
/// <summary>
/// Sends Unicode (UTF16) string to foreground window.
/// </summary>
/// <param name="inputString">String to be sent to foreground window.</param>
internal static void Send(string inputString)
{
if (inputString == string.Empty)
{ return; }
char[] chars = inputString.ToCharArray();
INPUT[] pInputs = new INPUT[chars.Length * 2];
for (int i = 0; i < chars.Length; i++)
{
UInt16 unicode = chars[i];
pInputs[i * 2] = new INPUT();
pInputs[i * 2].type = INPUT_KEYBOARD;
pInputs[i * 2].ki.wVk = 0;
pInputs[i * 2].ki.wScan = unicode;
pInputs[i * 2].ki.dwFlags = KEYEVENTF_UNICODE;
pInputs[i * 2].ki.time = 0;
pInputs[i * 2].ki.dwExtraInfo = SetMessageExtraInfo(IntPtr.Zero);
pInputs[i * 2 + 1] = new INPUT();
pInputs[i * 2 + 1].type = INPUT_KEYBOARD;
pInputs[i * 2 + 1].ki.wVk = 0;
pInputs[i * 2 + 1].ki.wScan = unicode;
pInputs[i * 2 + 1].ki.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP;
pInputs[i * 2 + 1].ki.time = 0;
pInputs[i * 2 + 1].ki.dwExtraInfo = SetMessageExtraInfo(IntPtr.Zero);
}
uint nSent = SendInput((uint)chars.Length * 2, pInputs, Marshal.SizeOf(typeof(INPUT)));
if (nSent == 0)
{
Debug.WriteLine("SendInput error " + GetLastError().ToString()); // error 87 : "The parameter is incorrect."
}
}
在记事本或 VS 等桌面应用程序中,代码可以正常工作,但在其他应用程序中,它不适用于简单的英文字母和标点符号。 像“íáó”这样带有特殊字符的字符串可以显式/普遍使用,但像“My car”这样的字符串却不行。显然,“我的车”中 chars 的 utf-16 值很低,小于 100; á 和 í 的值分别为 225 和 237。看似表面上的区别。 有人知道使用 SendInput 将常规英文字母作为 Unicode 发送到任意窗口的方法吗?
【问题讨论】:
-
您在使用哪些应用时遇到问题?
-
Chrome 搜索框、Chrome 多功能框和在 Windows 上安装可执行文件的设置应用程序中的文本框。
-
为什么不使用 UI 自动化