如何在 C 中捕获击键或鼠标按钮的事件 "down" "up"

How to capture event "down" "up" for a keystroke or a mouse button in C

我发现了很多使用 X11linux/input.h 的例子,不幸的是我在 Cygwin 上 linux/input.h 不存在。

我想要一个可以用来检测事件的简单示例,例如:

我想找到一个可以在 Cygwin/Linux 上工作并可选地在 Windows/OSX 上工作的解决方案。

可能吗?

到目前为止,我找到了 1 个使用 X11 的解决方案:

#include <stdio.h>
#include <X11/Xlib.h>

char *key_name[] = {
    "first",
    "second (or middle)",
    "third",
    "fourth",  // :D
    "fivth"    // :|
};

int main(int argc, char **argv)
{
    Display *display;
    XEvent xevent;
    Window window;

    if( (display = XOpenDisplay(NULL)) == NULL )
        return -1;

    window = DefaultRootWindow(display);
    XAllowEvents(display, AsyncBoth, CurrentTime);

    XGrabPointer(display, 
                 window,
                 1, 
                 PointerMotionMask | ButtonPressMask | ButtonReleaseMask , 
                 GrabModeAsync,
                 GrabModeAsync, 
                 None,
                 None,
                 CurrentTime);

    while(1) {
        XNextEvent(display, &xevent);
        switch (xevent.type) {
            case ButtonPress:
                printf("Button pressed  : %s\n", key_name[xevent.xbutton.button - 1]);
                break;
            case ButtonRelease:
                printf("Button released : %s\n", key_name[xevent.xbutton.button - 1]);
                break;
        }
    }

    return 0;
}

构建
gcc foo.c -lX11

不幸的是,必须启动 Xserver startxwin& 并且鼠标指针必须位于 X 服务器内 window。所以这不是一个好的解决方案。

另一种方法是使用 ncurses,但似乎状态 key-downkey-up 是不可能的。

下面的示例在 cygwin 上不起作用,因为 conio.h 不是 POSIX:

#include <stdio.h>
#include <conio.h>
char ch;
void main(){
    while(1){
        if(kbhit()){ //kbhit is 1 if a key has been pressed
            ch=getch();
            printf("pressed key was: %c", ch);
        }
    }
}

conio.h is a C header file used mostly by MS-DOS compilers to provide console input/output.[1] It is not part of the C standard library or ISO C, nor is it defined by POSIX.

你好像想做一个跨平台的程序。我怀疑您是否能够使用仅 Linux 的库解决此问题。我的建议是:

  1. 放弃 X,转而使用 Qt 或 GTK。
  2. 制作一个使用 Windows.h 中的工具侦听关键事件的模块,仅当用户使用 Windows 时才编译。随着项目的发展,您迟早需要为其他内容执行此操作。