2017-07-10 112 views
2

我有一個C++項目,我在其中使用Winapi開發一個帶有按鈕的窗口,並且我想在它被徘徊時更改按鈕的文本。例如,在徘徊時將「點擊我」更改爲「立即點擊我!」。我試過搜索,但我還沒有找到任何好的方法來做到這一點。Winapi檢測按鈕懸停

我注意到,當用戶懸停時,收到WM_NOTIFY消息,但我不知道如何確保它已被鼠標懸停調用。我發現我可以使用TrackMouseEvent來檢測懸停,但它僅限於一段時間,我希望在用戶每次懸停按鈕時執行一次操作。

這是我如何創建一個按鈕:

HWND Button = CreateWindow("BUTTON", "Click me", 
     WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON | BS_NOTIFY, 
     20, 240, 120, 20, 
     hwnd, (HMENU)101, NULL, NULL); 

這我的窗口過程:

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) 
{ 

    switch (msg) 
    { 
    case WM_NOTIFY: 
    { 
     //??? Here is where I get a message everytime I hover the button, But I don't know any proper way to see if it has been executed by the button. 
    } 
    case WM_CREATE: //On Window Create 
    { 
     //... 
    } 
    case WM_COMMAND: //Command execution 
    { 
     //... 
     break; 
    } 
    case WM_DESTROY: //Form Destroyed 
    { 
     PostQuitMessage(0); 
     break; 
    } 
    } 
    return DefWindowProc(hwnd, msg, wParam, lParam); 
} 

回答

2

假設你正在使用the common controls沒有爲WM_NOTIFY消息BCN_HOTITEMCHANGE通知代碼。該消息包含NMBCHOTITEM結構,其中包含有關鼠標是否進入或離開懸停區域的信息。

下面是一個例子:

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) 
{ 
    switch(msg) 
    { 
     case WM_NOTIFY: 
     { 
      LPNMHDR header = *reinterpret_cast<LPNMHDR>(lParam); 

      switch (header->code) 
      { 
       case BCN_HOTITEMCHANGE: 
       { 
        NMBCHOTITEM* hot_item = reinterpret_cast<NMBCHOTITEM*>(lParam); 

        // Handle to the button 
        HWND button_handle = header->hwndFrom; 

        // ID of the button, if you're using resources 
        UINT_PTR button_id = header->idFrom; 

        // You can check if the mouse is entering or leaving the hover area 
        bool entering = hot_item->dwFlags & HICF_ENTERING; 

        return 0; 
       } 
      } 

      return 0; 
     } 
    } 

    return DefWindowProcW(hwnd, msg, wParam, lParam); 
} 
+0

謝謝你的回答,但你知道我該如何實現NMBCHOTITEM?據我所知,我需要包含commctrl.h,但它給了windows.h許多isues – MrDick

0

您可以檢查WM_NOTIFY消息的代碼,看看它是否是NM_HOVER消息。

switch(msg) 
{ 
case WM_NOTIFY: 
    if(((LPNMHDR)lParam)->code == NM_HOVER) 
    { 
     // Process the hover message 
    } 
    else if (...) // any other WM_NOTIFY messages you care about 
    {} 
}