首页 > 解决方案 > XTestFakeKeyEvent 调用被吞没

问题描述

我试图欺骗击键;更准确地说:我正在重放一些击键,这些击键都应该在特定时间发送- 有时同时发送几个(或至少尽可能靠近)。

使用 XTestFakeKeyEvent 实现这个,我遇到了一个问题。虽然到目前为止我所写的大部分内容都按预期工作并在正确的时间发送事件,但有时其中一些会失败。XTestFakeKeyEvent 永远不会返回零(这表明失败),但这些事件似乎永远不会到达我试图将它们发送到的应用程序。我怀疑这可能是由于调用频率太高(有时 100+/秒),因为当每秒有大量击键时,它看起来更容易失败。

一个小程序来说明我在做什么,为了简洁起见,不完整且没有错误检查:

// #includes ...

struct action {
    int time; // Time where this should be executed.
    int down; // Keydown or keyup?
    int code; // The VK to simulate the event for.
};

Display *display;

int nactions;           // actions array length.
struct action *actions; // Array of actions we'll want to "execute".

int main(void)
{
    display = XOpenDisplay(NULL);

    nactions = get_actions(&actions);

    int cur_time;
    int cur_i = 0;
    struct action *cur_action;

    // While there's still actions to execute.
    while (cur_i < nactions) {
        cur_time = get_time();
        cur_action = actions + cur_i;

        // For each action that is (over)due.
        while ((cur_action = actions + cur_i)->time <= cur_time) {
            cur_i++;

            XTestFakeKeyEvent(display, cur_action->code,
                cur_action->down, CurrentTime);
            XFlush(display);
        }

        // Sleep for 1ms.
        nanosleep((struct timespec[]){{0, 1000000L}}, NULL);
    }
}

我意识到上面的代码对我的情况非常具体,但我怀疑这是一个更广泛的问题——这也是我在这里问这个问题的原因。

您可以/应该多久刷新一次 XEvent 是否有限制?我发送的应用程序是否会成为问题,可能无法足够快地阅读它们?

标签: x11

解决方案


已经有一段时间了,但经过一些修修补补,结果发现我在按键和按键之间的延迟太低了。将其设置为 15 毫秒后,应用程序将操作正确地注册为击键,并且(仍然)具有非常高的准确性。

回想起来我觉得有点傻,但我确实觉得这可能是其他人也可能绊倒的事情。


推荐阅读