模拟输入:按下,保持和释放键 [英] Simulating input: key pressed, hold and release

查看:107
本文介绍了模拟输入:按下,保持和释放键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试模拟用户按下某个键,将其按住一定的时间间隔,然后释放它.我已经尝试使用SendKeys.Send()来实现此功能,但是我无法弄清楚如何控制按键的持续时间.

I am trying to simulate a user pressing a key, holding it for some specific time interval, and then releasing it. I have tried to implement this using SendKeys.Send(), but I cannot figure out how to control the duration of how long the key is pressed.

我不想一遍又一遍地发送相同的密钥;我想要一个按键按下和一个按键按下事件.

I don't want to just keep sending the same key over and over; I want a single key-down and a single key-up event.

例如,我有这样的代码:

For example, I have code like this:

//when i press this button, will sent keyboard key "A", i want to hold it until i release

private void start_btn_Click(object sender, EventArgs e)
{
    testSent();
}

//how should i hold it for a timer???
private void testSent()
{
    SendKeys.Send("A");
}

推荐答案

如果您希望接收程序在一段时间后仅看到按下事件,然后再看到按下事件,则需要使用其他API比SendKeys.那只发送整个键击,即按下键和按下键.您可以通过调用本机Windows SendInput()函数来执行所需的操作.

If you want the receiving program to see just the key-down event followed by a key-up event some period of time later, you will need a different API than SendKeys. That one only sends entire key-strokes, i.e. with key-down and key-up. You may be able to do what you want by p/invoking the native Windows SendInput() function.

我还没有使用过它,但是您可能会发现 Windows输入模拟器是有用的托管代码您需要的API的包装器.

I haven't used it, but you may find that the Windows Input Simulator is a useful managed code wrapper for the API you need.

假设您弄清楚了如何结束适当的关键事件,那么按时进行是很简单的:

Assuming you figure out how to end the appropriate key events, doing it on a timed basis is trivial:

private static readonly TimeSpan _keyDownInterval = ...; // initialize as desired

private async void start_btn_Click(object sender, EventArgs e)
{
    SendKeyDown();
    await Task.Delay(_keyDownInterval);
    SendKeyUp();
}

// These two are implemented using whatever mechanism you prefer,
// e.g. p/invoke `SendInput()`, using the Windows Input Simulator library, or whatever.
private void SendKeyDown() { ... }
private void SendKeyUp() { ... }


以下是有关堆栈溢出的一些相关问题:
将密钥发送到WPF浏览器控件
C#p/Invoke如何使用适用于DirectX游戏的SendInput模拟keyPRESS事件


Here are some related questions on Stack Overflow:
Send keys to WPF Browser control
C# p/Invoke How to simulate a keyPRESS event using SendInput for DirectX games

都没有专门解决您的问题,但是都包含了有关SendInput()用法的一些讨论.

Neither specifically address your question, but they both include some discussion on the usage of SendInput().

这篇关于模拟输入:按下,保持和释放键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆