2014-04-23 56 views
0

我正在嘗試編寫一個簡單的可重用類來封裝基本托盤圖標的功能。這是我第一個使用C++的「項目」,我遇到了一些問題:爲托盤圖標創建的僅消息窗口沒有收到任何消息。該圖標在托盤中可見,並具有正確的工具提示,但點擊該圖標不會將任何消息發送到我不可見的窗口。消息窗口沒有從托盤圖標接收消息

要測試功能WindowProcedure是所謂的,我加了一個printf聲明,輸出的是被調用的函數在創建時的4倍,但沒有更多的,即使我點擊通知圖標。

爲什麼我的窗口沒有收到來自托盤圖標的任何消息?

這是我已經成功地寫:

TrayIcon.h

class TrayIcon { 

    public: 
     TrayIcon(); 
     ~TrayIcon(); 
     void Show(); 
     /*...*/ 
     static void Initialize(); 


    private: 
     static LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); 
     /*...*/  
}; 

TrayIcon.cpp

// Static initializer 
int TrayIcon::_idCounter = 1; 
void TrayIcon::Initialize() // This method is called just once 
{ 
    // Registers the class for the tray windows 
    WNDCLASSEX wx = {}; 
    wx.lpfnWndProc = TrayIcon::WindowProcedure; 
    wx.lpszClassName = TRAYICON_WINDOW_CLASSNAME; 
    wx.cbSize = sizeof(WNDCLASSEX); 
    RegisterClassEx(&wx); 
} 

// Constructor 
TrayIcon::TrayIcon() 
{ 
    // Creates an hidden message-only window 
    HWND hWnd = CreateWindowEx(0, TRAYICON_WINDOW_CLASSNAME, "trayiconwindow", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL); 
    SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG)this); 

    // Creates the notify icon 
    NOTIFYICONDATA icon; 
    memset(&icon, 0, sizeof(NOTIFYICONDATA)) ; 
    icon.cbSize = sizeof(NOTIFYICONDATA); 
    icon.hWnd = hWnd; 
    icon.uID = TrayIcon::_idCounter++; 
    icon.uCallbackMessage = WM_TRAYICON; //Set up our invented Windows Message 
    icon.uFlags = NIF_MESSAGE; 
    this->_iconData = icon; 
} 

// Shows the tray icon 
void TrayIcon::Show() 
{ 
    // ... 
    Shell_NotifyIcon(NIM_ADD, &this->_iconData); 
} 

// Processes the messages received by the hidden window for each icon 
LRESULT CALLBACK TrayIcon::WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) 
{ 
    TrayIcon* icon = (TrayIcon*)GetWindowLongPtr(hwnd, GWLP_USERDATA); 
    printf("Window Procedure called.\n\r"); 
    return DefWindowProc(hwnd, message, wParam, lParam); 
} 

這就是我如何使用類:

int main() 
{ 
    // Creates a new Tray icon 
    TrayIcon::Initialize(); 
    TrayIcon* icon = new TrayIcon(); 
    icon->SetTooltip("Foo Tooltip"); 
    icon->SetIcon(...); 
    icon->Show(); 

    // Waits for user input 
    void* tmp; 
    cin >> tmp; 
    return 0; 
} 

謝謝你的時間。

回答

2

您需要某種形式的消息循環,而不是阻塞調用來輸入內容。嘗試規範的消息循環:

MSG msg; 
while (GetMessage(&msg, nullptr, 0, 0)) { 
    TranslateMessage(&msg); 
    DispatchMessage(&msg); 
} 
+0

謝謝,它的工作完美。我打賭我昨天嘗試了這個,但它沒有奏效。午夜後我絕對應該停止編程! –