模拟击键并不总是有效

时间:2013-01-20 21:28:24

标签: c# winapi keyboard

我有一个应用程序,在用户请求中将一些键盘命令发送到另一个程序。为此,我使用http://inputsimulator.codeplex.com/

问题在于,不时会向目标应用程序接收键盘按下。

我已经编写了一个模拟这个的测试程序,见下文。 有些运行,它运行良好,有些运行它经常失败。是什么造成的?我该怎样预防呢? 当然,一种方法是在键盘按下之前添加延迟,但问题是延迟合理的时间长短。理想情况下,我想避免延迟。

private void SendKeyTest(IntPtr mainWindow, IntPtr receiverWindow)
{
    int index = 0;

    while (!_cancle)
    {
        // Set receiver application as active
        NativeMethods.SetForegroundWindow(receiverWindow);

        // Send the keyboard presses
        InputSimulator.SimulateTextEntry(string.Format("{0,5:N0}\n", index++));

        // Return to the main application
        NativeMethods.SetForegroundWindow(mainWindow);

        Thread.Sleep(500);
    }
}

0 个答案:

没有答案