8

我想知道使用 C# 发送击键的最快方法是什么。目前我正在使用SendKeys.Send()and SendKeys.SendWait()with SendKeys.Flush().

我正在使用以下代码来计算它们两个工作所需的时间:

Stopwatch sw1 = new Stopwatch();
sw1.Start();
for (int a = 1; a <= 1000; a++)
{
    SendKeys.Send("a");
    SendKeys.Send("{ENTER}");
}
sw1.Stop();

和:

Stopwatch sw2 = new Stopwatch();
sw2.Start();
for (int b = 1; b <= 1000; b++)
{
    SendKeys.SendWait("b");
    SendKeys.SendWait("{ENTER}");
    SendKeys.Flush();
}
sw2.Stop();

2的结果是:

Result 1: 40119 milliseconds
Result 2: 41882 milliseconds

现在,如果我们将SendKeys.Flush()第二个测试放在循环之外,我们会得到:

Result 3: 46278 milliseconds

我想知道为什么代码中的这些更改会使速度大不相同。

我还想知道是否有一种更快的方式来发送许多击键,因为我的应用程序经常这样做。(这些测试是在一个非常慢的上网本上完成的)

谢谢!

4

2 回答 2

12

If you have a lot of text to push to a client, you may notice that SendKeys is really sluggish. You can vastly speed things up by using the clipboard. The idea is to put the text you wish to "type" into a target text box in the clipboard and then send a CTRL-V to the target application to paste that text. Here's an illustration:

Clipboard.Clear();  // Always clear the clipboard first
Clipboard.SetText(TextToSend);
SendKeys.SendWait("^v");  // Paste

I found this worked well for me with a cordless bar code scanner that talks via WiFi to a host app that sends long bar codes to a web app running in Google Chrome. It went from tediously pecking out 30 digits over about 4 seconds to instantly pasting all in under a second.

One obvious downside is that this can mess with your user's use of the clipboard. Another is that it doesn't help if you intend to send control codes like TAB or F5 instead of just plain old text.

于 2012-07-10T20:21:33.600 回答
11

SendWait()速度较慢,因为它等待消息已被目标应用程序处理。相反,该Send()函数不会等待并尽快返回。如果应用程序有点忙,则差异可能会更加明显。

如果您调用Flush(),您将停止您的应用程序来处理与键盘相关的所有事件,这些事件在消息队列中排队。如果您使用它们发送它们并没有太大意义,SendWait()并且您会减慢很多应用程序,因为它在循环内(想象Flush()作为一个选择性DoEvents()- 是的,它有所有缺点 - 它也被SendWait()自己调用)。

如果您对它的性能感兴趣(但它们总是受限于您的应用程序处理消息的速度),请在 MSDN 上阅读此内容。总之,您可以更改SendKeys类以使用该SendInput函数,而不是日志挂钩。作为快速参考,只需将此设置添加到您的 app.config 文件中:

<appSettings>
    <add key="SendKeys" value="SendInput"/>
</appSettings>

无论如何,新实现的目标不是速度,而是跨不同版本的 Windows 和选项的一致行为(我猜,提高的性能是一种副作用)。

于 2012-05-07T10:22:29.793 回答