赞
踩
- #include <QCoreApplication>
- #include <QDebug>
- #include <QAbstractNativeEventFilter>
- #include <QKeyEvent>
-
- #ifdef Q_OS_WIN
- #include <qt_windows.h>
- #elif defined(Q_OS_LINUX)
- #include <X11/Xlib.h>
- #include <X11/Xutil.h>
- #endif
-
- class KeyboardInterceptor : public QAbstractNativeEventFilter
- {
- public:
- bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) override
- {
- Q_UNUSED(eventType);
- Q_UNUSED(result);
-
- if (eventType == "windows_generic_MSG" && message != nullptr)
- {
- MSG *msg = static_cast<MSG *>(message);
-
- if (msg->message == WM_KEYDOWN || msg->message == WM_SYSKEYDOWN)
- {
- // 拦截按下事件
- qDebug() << "Key down - VK code: " << msg->wParam;
- return true; // 返回true以拦截事件
- }
- else if (msg->message == WM_KEYUP || msg->message == WM_SYSKEYUP)
- {
- // 拦截释放事件
- qDebug() << "Key up - VK code: " << msg->wParam;
- return true; // 返回true以拦截事件
- }
- }
-
- #ifdef Q_OS_LINUX
- // 在Linux上拦截键盘事件
- if (eventType == "xcb_generic_event_t" && message != nullptr)
- {
- xcb_generic_event_t *ev = static_cast<xcb_generic_event_t *>(message);
-
- if (ev->response_type & XCB_EVENT_MASK_KEY_PRESS)
- {
- xcb_key_press_event_t *keyEvent = static_cast<xcb_key_press_event_t *>(message);
-
- // 拦截按下事件
- qDebug() << "Key down - Key code: " << keyEvent->detail;
- return true; // 返回true以拦截事件
- }
- else if (ev->response_type & XCB_EVENT_MASK_KEY_RELEASE)
- {
- xcb_key_release_event_t *keyEvent = static_cast<xcb_key_release_event_t *>(message);
-
- // 拦截释放事件
- qDebug() << "Key up - Key code: " << keyEvent->detail;
- return true; // 返回true以拦截事件
- }
- }
- #endif
-
- return false; // 返回false以继续处理事件
- }
- };
-
- int main(int argc, char *argv[])
- {
- QCoreApplication app(argc, argv);
-
- KeyboardInterceptor interceptor;
- app.installNativeEventFilter(&interceptor);
-
- return app.exec();
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。