我正在使用TestApiKeyboard.Type
项目中的方法在文本框中输入字符串。
/// <summary>
/// Types the specified text.
/// </summary>
/// <remarks>
/// Note that a combination of a combination of Key.Shift or Key.Capital and a Unicode point above 0xFE
/// is not considered valid and will not result in the Unicode point being types without
/// applying of the modifier key.
/// </remarks>
/// <param name="text">The text to type.</param>
public static void Type(string text)
{
foreach (char c in text)
{
// If code point is bigger than 8 bits, we are going for Unicode approach by setting wVk to 0.
if (c > 0xFE)
{
SendKeyboardKey(c, true, false, true);
SendKeyboardKey(c, false, false, true);
}
else
{
// We get the vKey value for the character via a Win32 API. We then use bit masks to pull the
// upper and lower bytes to get the shift state and key information. We then use WPF KeyInterop
// to go from the vKey key info into a System.Windows.Input.Key data structure. This work is
// necessary because Key doesn't distinguish between upper and lower case, so we have to wrap
// the key type inside a shift press/release if necessary.
int vKeyValue = NativeMethods.VkKeyScan(c);
bool keyIsShifted = (vKeyValue & NativeMethods.VKeyShiftMask) == NativeMethods.VKeyShiftMask;
Key key = (Key)(vKeyValue & NativeMethods.VKeyCharMask);
if (keyIsShifted)
{
Type(key, new Key[] { Key.Shift });
}
else
{
Type(key);
}
}
}
}
private static void SendKeyboardKey(ushort key, bool isKeyDown, bool isExtended, bool isUnicode)
{
var input = new NativeMethods.INPUT();
input.Type = NativeMethods.INPUT_KEYBOARD;
if (!isKeyDown)
{
input.Data.Keyboard.dwFlags |= NativeMethods.KEYEVENTF_KEYUP;
}
if (isUnicode)
{
input.Data.Keyboard.dwFlags |= NativeMethods.KEYEVENTF_UNICODE;
input.Data.Keyboard.wScan = key;
input.Data.Keyboard.wVk = 0;
}
else
{
input.Data.Keyboard.wScan = 0;
input.Data.Keyboard.wVk = key;
}
if (isExtended)
{
input.Data.Keyboard.dwFlags |= NativeMethods.KEYEVENTF_EXTENDEDKEY;
}
input.Data.Keyboard.time = 0;
input.Data.Keyboard.dwExtraInfo = IntPtr.Zero;
NativeMethods.SendInput(1, new NativeMethods.INPUT[] { input }, Marshal.SizeOf(input));
Thread.Sleep(100);
}
它可以工作,但它输入文本相当慢。我想提高速度。理想情况下,它应该立即设置文本(考虑将文本粘贴到文本字段中)。
有没有一种简单的方法可以在 C# 中实现它(一次将文本字段的文本设置为某个字符串)?