Qt NativeEventFilter

2172 ワード

NativeEventFilter、ローカルイベントフィルタ、Qtでは、システムメッセージまたはカスタムメッセージの処理が必要な場合に使用されます.関連するのはQA b s tractNativeEventFilterクラスと2つの関数(installNativeEventFilter、removeNativeEventFilter)
1 QUbstractNativeEventFilter
このクラスは比較的簡単で、純粋な虚のクラスで、1つの虚のインタフェースしかありません:
virtual bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) = 0
実際にはQLPplicationレベルでシステムメッセージを処理するのが一般的である.2つの方法があります.
1、QAPplicationから一つのクラスを派生し、QCBstractNativeEventFilterを継承し、nativeEventFilterインタフェースを実現する
demo:
class MyApp : public QApplication , public QAbstractNativeEventFilter 
{....};

2、QA bstractNativeEventFilterサブクラスを1つ書き、QA p r icationにこのフィルタをインストールすればよい.QA p r icationの2つの関数に関連する.
void installNativeEventFilter(QAbstractNativeEventFilter *filterObj) void removeNativeEventFilter(QAbstractNativeEventFilter *filterObject)
demo:
#include 
#include 

class MyAppNativeEventFilter  : public QAbstractNativeEventFilter 
{
    virtual bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) override;
};

int main(int argc,   char* argv [])
{
    QApplication app(argc, argv);
    MyAppNativeEventFilter filter;
    app.installNativeEventFilter(&filter);
    return app.run();
}

二nativeEventFilterインタフェース実装
Qt assistantにはいくつかの事例があります.
例えばwindowsで
virtual bool nativeEventFilter(const QByteArray &eventType, void *message, long *) override
{
    if(eventType == "windows_generic_MSG" || eventType == "windows_dispatcher_MSG")
    {
        MSG* pMsg = reinterpret_cast(message);
        if(pMsg->message == WM_COPYDATA)
        {
            qDebug()<

1、文書にはnativeEventFilterの戻り値について説明があります.
In your reimplementation of this function, if you want to filter the message out, i.e. stop it being handled further, return true; otherwise return false.
2、システムによってeventTypeが違う
X 11は「xcb_generic_event_t」
macOSは「mac_generic_NSEvent」
Windowsは「windows_generic_MSG」と「windows_dispatcher_MSG」