【问题标题】:Possible targeting SendInput()?可能以 SendInput() 为目标?
【发布时间】:2019-05-13 16:42:09
【问题描述】:

在 C# 中使用 SendInput() 发送长击键。问题是使用它时,它在调用时适用于所有程序。是否可以将其定位为仅适用于特定程序?就像在使用 FindWindow 的 PostMessage() 中一样。

我的 SendInput():

[DllImport("user32.dll")]
    internal static extern uint SendInput(
        uint nInputs,
        [MarshalAs(UnmanagedType.LPArray), In] INPUT[] pInputs,
        int cbSize);

    public void KeySend(VirtualKeyShort key)
    {
        INPUT[] Inputs = new INPUT[1];
        INPUT Input = new INPUT();

        Input.type = 1;
        Input.U.ki.wVk = key;
        Inputs[0] = Input;


        SendInput(1, Inputs, INPUT.Size);
    }

    public void KeyUp(VirtualKeyShort key)
    {
        INPUT[] Inputs = new INPUT[1];
        INPUT Input = new INPUT();

        Input.type = 1; 
        Input.U.ki.wVk = key;
        Input.U.ki.dwFlags = KEYEVENTF.KEYUP;
        Inputs[0] = Input;


        SendInput(1, Inputs, INPUT.Size);
    }

谢谢。

【问题讨论】:

  • SendInput 的重点是重用操作系统输入处理逻辑。这种逻辑包括尊重焦点。如果你不想尊重焦点,你不应该要求使用这样做的逻辑。

标签: c# user32


【解决方案1】:

在启动您的 sendinput 之前,如果您想将密钥发送到记事本,您可以这样做(例如):

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

class Program {
    static void Main(string[] args) {
        var proc = Process.GetProcessesByName("notepad");
        if (proc.Length > 0) {
            SetForegroundWindow(proc[0].MainWindowHandle);
        }
    }
    [DllImport("user32.dll")]
    private static extern bool SetForegroundWindow(IntPtr hWnd);

}

您的窗口应用程序将获得焦点并可以接收密钥

如果你想枚举所有应用程序,你可以使用 EnumWindows

【讨论】:

    猜你喜欢
    • 2018-07-13
    • 2021-12-05
    • 1970-01-01
    • 2021-11-25
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    相关资源
    最近更新 更多