关于SendInput() 的一些说明,与您尝试做的事情有关。
- 此函数接受INPUT 结构的数组。您需要在一次调用中将所有按键传递给此函数。这包括 Key 和 Key 修饰符(Control、Shift、ALT、Menu 等)
- 输入被发送到当前输入接收者,因此您需要确保用于接收按键的窗口是聚焦的(或其父窗口或主窗口,即实际处理按键的窗口压力机)
- 如果目标窗口属于不同的线程,对
SetFocus()的调用可能会失败,所以我们预先附加到那个线程。
- 如果父主窗口被最小化,您需要事先将其打开,以确保它会接收焦点,然后是我们的输入。
这里我用GetCurrentThreadId()和GetWindowThreadProcessId()比较,来验证调用者Thread和目标Thread是否不同。
如果它们不相同,则调用AttachThreadInput()。
如果目标主窗口被最小化(参见对IsIconic() 的调用),它会被恢复,调用SetWindowPlacement() 并使用BringWindowToTop() 被带到前台。
然后对SetFocus() 的调用将焦点移动到目标句柄(假设它可以接收焦点,即 - 该函数无论如何都应该返回成功)。
最后,您收集所有需要发送到不同INPUT 结构(每个键修饰符在其自己的结构中)的所有密钥,并对SendInput() 进行一次调用。
例如:
发送向上目标句柄的关键:
IntPtr handle = [The selected handle];
bool result = NativeMethods.SendKeyboardInput(handle, Keys.Up, null);
发送控制+转移+家:
var modifiers = new[] { Keys.ShiftKey, Keys.ControlKey};
bool result = NativeMethods.SendKeyboardInput(handle, Keys.Home, modifiers);
这是它的工作原理:
标准 PictureBox 无法聚焦,因此在调用 SetFocus() 时会看到 Button 闪烁
Sample Project for testing (Google Drive)
本机方法:
internal class NativeMethods {
public static bool SendKeyboardInput(IntPtr hWnd, Keys key, Keys[] modifiers = null, int delay = 0)
{
if (hWnd != IntPtr.Zero) {
uint targetThreadID = GetWindowThreadProcessId(hWnd, IntPtr.Zero);
uint currentThreadID = GetCurrentThreadId();
if (targetThreadID != currentThreadID) {
try {
if (!AttachThreadInput(currentThreadID, targetThreadID, true)) return false;
var parentWindow = GetAncestor(hWnd, GetAncestorFlags.GA_ROOT);
if (IsIconic(parentWindow)) {
if (!RestoreWindow(parentWindow)) return false;
}
if (!BringWindowToTop(parentWindow)) return false;
if (SetFocus(hWnd) == IntPtr.Zero) return false;
}
finally {
AttachThreadInput(currentThreadID, targetThreadID, false);
}
}
else {
SetFocus(hWnd);
}
}
var flagsKeyDw = IsExtendedKey(key) ? KeyboardInputFlags.ExtendedKey : KeyboardInputFlags.KeyDown;
var flagsKeyUp = KeyboardInputFlags.KeyUp | (IsExtendedKey(key) ? KeyboardInputFlags.ExtendedKey : 0);
var inputs = new List<INPUT>();
var input = new INPUT(SendInputType.InputKeyboard);
// Key Modifiers Down
if (!(modifiers is null)) {
foreach (var modifier in modifiers) {
input.Union.Keyboard.Flags = KeyboardInputFlags.KeyDown;
input.Union.Keyboard.VirtKeys = (ushort)modifier;
inputs.Add(input);
}
}
// Key Down
input.Union.Keyboard.Flags = flagsKeyDw | KeyboardInputFlags.Unicode;
input.Union.Keyboard.VirtKeys = (ushort)key;
inputs.Add(input);
// Key Up
input.Union.Keyboard.Flags = flagsKeyUp | KeyboardInputFlags.Unicode;
input.Union.Keyboard.VirtKeys = (ushort)key;
inputs.Add(input);
// Key Modifiers Up
if (!(modifiers is null)) {
foreach (var modifier in modifiers) {
input.Union.Keyboard.Flags = KeyboardInputFlags.KeyUp;
input.Union.Keyboard.VirtKeys = (ushort)modifier;
inputs.Add(input);
}
}
uint sent = SendInput((uint)inputs.Count(), inputs.ToArray(), Marshal.SizeOf<INPUT>());
return sent > 0;
}
private static Keys[] extendedKeys = { Keys.Up, Keys.Down, Keys.Left, Keys.Right, Keys.Home, Keys.End, Keys.Prior, Keys.Next, Keys.Insert, Keys.Delete };
private static bool IsExtendedKey(Keys key) => extendedKeys.Contains(key);
// https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-input
[StructLayout(LayoutKind.Sequential)]
public struct INPUT {
public SendInputType InputType;
public InputUnion Union;
public INPUT(SendInputType type) {
InputType = type;
Union = new InputUnion();
}
}
public enum SendInputType : uint {
InputMouse = 0,
InputKeyboard = 1,
InputHardware = 2
}
[StructLayout(LayoutKind.Explicit)]
public struct InputUnion {
[FieldOffset(0)]
public MOUSEINPUT Mouse;
[FieldOffset(0)]
public KEYBDINPUT Keyboard;
[FieldOffset(0)]
public HARDWAREINPUT Hardware;
}
[StructLayout(LayoutKind.Sequential)]
public struct MOUSEINPUT {
public int dx;
public int dy;
public uint mouseData;
public MouseEventdwFlags dwFlags;
public uint time;
public IntPtr dwExtraInfo;
}
// https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-keybdinput
[StructLayout(LayoutKind.Sequential)]
public struct KEYBDINPUT {
public ushort VirtKeys;
public ushort wScan;
public KeyboardInputFlags Flags;
public uint time;
public IntPtr dwExtraInfo;
}
[StructLayout(LayoutKind.Sequential)]
public struct HARDWAREINPUT {
public int uMsg;
public short wParamL;
public short wParamH;
}
[Flags]
public enum MouseEventdwFlags : uint {
MOUSEEVENTF_MOVE = 0x0001,
MOUSEEVENTF_LEFTDOWN = 0x0002,
MOUSEEVENTF_LEFTUP = 0x0004,
MOUSEEVENTF_RIGHTDOWN = 0x0008,
MOUSEEVENTF_RIGHTUP = 0x0010,
MOUSEEVENTF_MIDDLEDOWN = 0x0020,
MOUSEEVENTF_MIDDLEUP = 0x0040,
MOUSEEVENTF_XDOWN = 0x0080,
MOUSEEVENTF_XUP = 0x0100,
MOUSEEVENTF_WHEEL = 0x0800,
MOUSEEVENTF_VIRTUALDESK = 0x4000,
MOUSEEVENTF_ABSOLUTE = 0x8000
}
[Flags]
public enum KeyboardInputFlags : uint {
KeyDown = 0x0,
ExtendedKey = 0x0001,
KeyUp = 0x0002,
Scancode = 0x0008,
Unicode = 0x0004
}
// https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-windowplacement
[StructLayout(LayoutKind.Sequential)]
public struct WINDOWPLACEMENT {
public int length;
public WplFlags flags;
public SW_Flags showCmd;
public POINT ptMinPosition;
public POINT ptMaxPosition;
public RECT rcNormalPosition;
}
public enum WplFlags : uint {
WPF_ASYNCWINDOWPLACEMENT = 0x0004, // If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request.
WPF_RESTORETOMAXIMIZED = 0x0002, // The restored window will be maximized, regardless of whether it was maximized before it was minimized. This setting is only valid the next time the window is restored. It does not change the default restoration behavior.
// This flag is only valid when the SW_SHOWMINIMIZED value is specified for the showCmd member.
WPF_SETMINPOSITION = 0x0001 // The coordinates of the minimized window may be specified. This flag must be specified if the coordinates are set in the ptMinPosition member.
}
[Flags]
public enum SW_Flags : uint {
SW_HIDE = 0X00,
SW_SHOWNORMAL = 0x01,
SW_MAXIMIZE = 0x03,
SW_SHOWNOACTIVATE = 0x04,
SW_SHOW = 0x05,
SW_MINIMIZE = 0x06,
SW_RESTORE = 0x09,
SW_SHOWDEFAULT = 0x0A,
SW_FORCEMINIMIZE = 0x0B
}
public enum GetAncestorFlags : uint {
GA_PARENT = 1, // Retrieves the parent window.This does not include the owner, as it does with the GetParent function.
GA_ROOT = 2, // Retrieves the root window by walking the chain of parent windows.
GA_ROOTOWNER = 3 // Retrieves the owned root window by walking the chain of parent and owner windows returned by GetParent.
}
[StructLayout(LayoutKind.Sequential)]
public class POINT {
public int x;
public int y;
public POINT(int x, int y) {
this.x = x;
this.y = y;
}
public Point ToPoint() => new Point(this.x, this.y);
public PointF ToPointF() => new PointF((float)this.x, (float)this.y);
public POINT FromPoint(Point p) => new POINT(p.X, p.Y);
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT {
public int Left;
public int Top;
public int Right;
public int Bottom;
public RECT(int left, int top, int right, int bottom) {
Left = left; Top = top; Right = right; Bottom = bottom;
}
public Rectangle ToRectangle() => Rectangle.FromLTRB(Left, Top, Right, Bottom);
public Rectangle ToRectangleOffset(POINT p) => Rectangle.FromLTRB(p.x, p.y, Right + p.x, Bottom + p.y);
public RECT FromRectangle(RectangleF rectangle) => FromRectangle(Rectangle.Round(rectangle));
public RECT FromRectangle(Rectangle rectangle) => new RECT() {
Left = rectangle.Left,
Top = rectangle.Top,
Bottom = rectangle.Bottom,
Right = rectangle.Right
};
public RECT FromXYWH(int x, int y, int width, int height) => new RECT(x, y, x + width, y + height);
}
// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowplacement
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool GetWindowPlacement(IntPtr hWnd, [In, Out] ref WINDOWPLACEMENT lpwndpl);
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool SetWindowPlacement(IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl);
[DllImport("user32.dll", SetLastError = true)]
internal static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr voidProcessId);
// https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentthreadid
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern uint GetCurrentThreadId();
// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-attachthreadinput
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool AttachThreadInput([In] uint idAttach, [In] uint idAttachTo, [In, MarshalAs(UnmanagedType.Bool)] bool fAttach);
[ResourceExposure(ResourceScope.None)]
[DllImport("User32", ExactSpelling = true, CharSet = CharSet.Auto)]
internal static extern IntPtr GetAncestor(IntPtr hWnd, GetAncestorFlags flags);
[DllImport("user32.dll")]
internal static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32.dll", SetLastError = true)]
internal static extern bool BringWindowToTop(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
internal static extern IntPtr SetFocus(IntPtr hWnd);
//https://learn.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-sendinput
[DllImport("user32.dll", SetLastError = true)]
internal static extern uint SendInput(uint nInputs, [In, MarshalAs(UnmanagedType.LPArray)] INPUT[] pInputs, int cbSize);
public static bool RestoreWindow(IntPtr hWnd)
{
var wpl = new WINDOWPLACEMENT() {
length = Marshal.SizeOf<WINDOWPLACEMENT>()
};
if (!GetWindowPlacement(hWnd, ref wpl)) return false;
wpl.flags = WplFlags.WPF_ASYNCWINDOWPLACEMENT;
wpl.showCmd = SW_Flags.SW_RESTORE;
return SetWindowPlacement(hWnd, ref wpl);
}
}