テキストボックスに文字列を入力するために、 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#でそれを実装する(テキストフィールドのテキストを一度にいくつかの文字列に設定する)簡単な方法はありますか?