2010-01-30 116 views
7

我想知道它是否可能在Qt應用程序中使用win32鍵盤鉤子函數(SetWindowsHookEx,SetWindowsHookEx)。是否可以在Qt應用程序中使用Win32鉤子

如果可能,請提供有關在Qt中使用SetWindowsHookEx,SetWindowsHookEx函數的示例代碼。

//更新截至2010年2月18日的//

我還沒有想出如何做,在QT呢。

但作爲解決方法,我創建了一個使用vC++ express版本的win32 dll,並將我的鉤子命令放入dll函數中。 我呼籲從Qt的DLL函數使用QLibrary類

/* hearder file code*/ 
    QLibrary *myLib; 
    typedef HHOOK (*MyPrototype)(HINSTANCE); 

/* source file code */ 
    myLib = new QLibrary("ekhook.dll"); 
    MyPrototype myFunction; 
    myFunction = (MyPrototype) myLib->resolve("Init"); 

的init()是在ekhook.dll這就是被調用的函數

回答

1

我相信這是可能的,肯定的。使用QWidget::winId

+1

如果您可以告訴我一個示例代碼,說明如何在SetWindowsHookEx中使用Qwidget :: winId,那將會非常有幫助。我不知道如何將這些連在一起。 – Mugunth 2010-01-30 23:43:59

4

我想知道同樣的事情,發現這個末了......幸得Voidrealms

該視頻足以說明如何使用以下代碼製作工作應用程序。

//Copied Code from YouTube Video 

#include <QtCore/QCoreApplication> 
#include <QDebug> 
#include <QTime> 
#include <QChar> 
#include <iostream> 
#include <windows.h> 
#pragma comment(lib, "user32.lib") 

HHOOK hHook = NULL; 

using namespace std; 

void UpdateKeyState(BYTE *keystate, int keycode) 
{ 
    keystate[keycode] = GetKeyState(keycode); 
} 

LRESULT CALLBACK MyLowLevelKeyBoardProc(int nCode, WPARAM wParam, LPARAM lParam) 
{ 
    //WPARAM is WM_KEYDOWn, WM_KEYUP, WM_SYSKEYDOWN, or WM_SYSKEYUP 
    //LPARAM is the key information 

    qDebug() << "Key Pressed!"; 

    if (wParam == WM_KEYDOWN) 
    { 
     //Get the key information 
     KBDLLHOOKSTRUCT cKey = *((KBDLLHOOKSTRUCT*)lParam); 

     wchar_t buffer[5]; 

     //get the keyboard state 
     BYTE keyboard_state[256]; 
     GetKeyboardState(keyboard_state); 
     UpdateKeyState(keyboard_state, VK_SHIFT); 
     UpdateKeyState(keyboard_state, VK_CAPITAL); 
     UpdateKeyState(keyboard_state, VK_CONTROL); 
     UpdateKeyState(keyboard_state, VK_MENU); 

     //Get keyboard layout 
     HKL keyboard_layout = GetKeyboardLayout(0); 

     //Get the name 
     char lpszName[0X100] = {0}; 

     DWORD dwMsg = 1; 
     dwMsg += cKey.scanCode << 16; 
     dwMsg += cKey.flags << 24; 

     int i = GetKeyNameText(dwMsg, (LPTSTR)lpszName, 255); 

     //Try to convert the key information 
     int result = ToUnicodeEx(cKey.vkCode, cKey.scanCode, keyboard_state, buffer, 4, 0, keyboard_layout); 
     buffer[4] = L'\0'; 

     //Print the output 
     qDebug() << "Key: " << cKey.vkCode << " " << QString::fromUtf16((ushort*)buffer) << " " << QString::fromUtf16((ushort*)lpszName); 

    } 

    return CallNextHookEx(hHook, nCode, wParam, lParam); 
} 

int main(int argc, char *argv[]) 
{ 
    QCoreApplication a(argc, argv); 


    hHook = SetWindowsHookEx(WH_KEYBOARD_LL, MyLowLevelKeyBoardProc, NULL, 0); 
    if (hHook == NULL) 
    { 
     qDebug() << "Hook Failed" << endl; 
    } 

    return a.exec(); 
} 
相關問題