2010-09-28 62 views
0

我目前正在研究一個應用程序,需要爲每個應用程序的系統菜單添加一個菜單 。我可以用EnumWindows函數來完成現有的 窗口。 對於新窗口(應用程序啓動後我的) 我試圖用windows鉤子做到這一點。更具體地說與CBTProc。 這是我卡住的地方。 我已經在應用程序中剝去了所有可能的東西, ,但是我有一個印象,我的dll中的程序根本不會調用 。SetWindowsHookEx,CBTProc和g ++ 3.4.5(mingw)

這裏的DLL的代碼:

#include <string> 
using std::string; 

#include <fstream> 
using std::ofstream; 

#include <windows.h> 

// --------------------------------------------------- 
extern "C" 
{ 
    void log(const string & msg) 
    { 
    ofstream out("out.log", std::ios_base::app); 
    out << msg; 
    out.flush(); 
    out.close(); 
    } 
    // --------------------------------------------------- 
    LRESULT CALLBACK CBTProc(int nCode, WPARAM wParam, LPARAM lParam) 
    { 
    log("CBTProc"); 
    return CallNextHookEx(0, nCode, wParam, lParam); 
    } 
    // --------------------------------------------------- 
} 

我編這與G ++ 3.4.5在Windows XP SP3 32位機器上:

g++ -shared -otest.dll test_dll.cpp 

下面是該應用程序

代碼
#include <iostream> 
using std::cout; 
using std::cin; 
using std::cerr; 
using std::endl; 

#include <string> 
using std::string; 

#include <windows.h> 

typedef void (*func)(); 

void run() 
{ 
    cout << "press enter to exit" << endl; 
    cin.get(); 
} 

void * loadProc(HMODULE mod, const char * procname) 
{ 
    void * retval = (void *)GetProcAddress(mod, procname); 
    if (retval == NULL) 
    cerr << "GetProcAddress(" << procname << ") failed" << endl; 
    return retval; 
} 

int main(int argc, char ** argv) 
{ 
    HMODULE dll = LoadLibrary("test.dll"); 
    if (dll == NULL) 
    { 
     cerr << "LoadLibrary failed" << endl; 
     return 1; 
    } 

    HOOKPROC proc = (HOOKPROC)loadProc(dll, "[email protected]"); 
    if (!proc) 
    return 1; 

    HHOOK callwnd = SetWindowsHookEx(WH_CBT, proc, dll, 0); 
    if (callwnd == NULL) 
    { 
     cerr << "SetWindowsHookEx failed for CBTProc" << endl; 
     return 1; 
    } 

    run(); 
    UnhookWindowsHookEx(callwnd); 

    return 0; 
} 

我用相同的設置編譯這個:

g++ -otest.exe test.cpp 

當我運行時,我沒有遇到任何錯誤,但是當我啓動新的應用程序時,在我的日誌文件中沒有任何文件 。

任何想法?

克, LDX

編輯:拼寫錯誤

回答

1

我建議你檢查以下內容:

  • 確保您的DLL有一個出口 (可使用dumpbin工具進行檢查)。 I 不知道g ++,但是在MSVC中它 對於使用 __declspec(dllexport)或在DEF文件中顯式地聲明導出狀態是必要的。

  • 確保您的主機應用程序 使用 導出函數(同 「DUMPBIN/EXPORTS Test.dll的」 顯示器)的正確名稱

  • 記住,你正在使用相對文件名out.log - 當DLL被加載到其他進程時,它將相對於主進程的當前目錄寫入。出於測試目的,最好使用OutputDebugString API並使用DbgView工具檢查結果。

很可能您的解決方案已經工作。注:在注入的DLL中使用STL通常不是一個好主意。確保你瞭解風險。