c#模拟键盘输入到指定位置
时间: 2023-07-27 09:19:22 浏览: 55
如果你想将模拟键盘输入发送到指定的位置,可以使用Windows API函数`SetForegroundWindow`和`SendInput`。以下是一个示例代码,它将模拟按下"Hello World"键,并将其发送到指定的文本框中:
```csharp
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
// 设置前台窗口并模拟键盘输入
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
private const int INPUT_KEYBOARD = 1;
private const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
private const uint KEYEVENTF_KEYUP = 0x0002;
[StructLayout(LayoutKind.Sequential)]
private struct INPUT
{
public int type;
public INPUTUNION union;
}
[StructLayout(LayoutKind.Explicit)]
private struct INPUTUNION
{
[FieldOffset(0)]
public KEYBDINPUT keyboardInput;
}
[StructLayout(LayoutKind.Sequential)]
private struct KEYBDINPUT
{
public ushort wVk;
public ushort wScan;
public uint dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
// 获取窗口句柄
Process process = Process.GetProcessesByName("YourProcessName")[0];
IntPtr hwnd = process.MainWindowHandle;
// 设置前台窗口
SetForegroundWindow(hwnd);
// 模拟键盘输入
string text = "Hello World";
foreach (char c in text)
{
INPUT[] inputs = new INPUT[2];
inputs[0].type = INPUT_KEYBOARD;
inputs[0].union.keyboardInput.wVk = 0;
inputs[0].union.keyboardInput.wScan = (ushort)c;
inputs[0].union.keyboardInput.dwFlags = KEYEVENTF_UNICODE;
inputs[0].union.keyboardInput.time = 0;
inputs[0].union.keyboardInput.dwExtraInfo = IntPtr.Zero;
inputs[1].type = INPUT_KEYBOARD;
inputs[1].union.keyboardInput.wVk = 0;
inputs[1].union.keyboardInput.wScan = (ushort)c;
inputs[1].union.keyboardInput.dwFlags = KEYEVENTF_UNICODE | KEYEVENTF_KEYUP;
inputs[1].union.keyboardInput.time = 0;
inputs[1].union.keyboardInput.dwExtraInfo = IntPtr.Zero;
SendInput(2, inputs, Marshal.SizeOf(typeof(INPUT)));
}
```
在代码中,我们首先使用`GetProcessesByName`函数获取指定进程的句柄,然后使用`SetForegroundWindow`函数将其设置为前台窗口。接下来,我们使用`SendInput`函数模拟键盘输入,将每个字符一个接一个地发送到指定的文本框中。你可以根据需要修改代码以适应你的应用程序。
阅读全文