3
votes

I need to change the cursor icon when the mouse hovers a certain HWND. I achieved the mouse cursor change with

SetClassLong(hWindow, GCL_HCURSOR, (LONG)LoadCursor (NULL, IDC_CROSS));

But it applies the cursor to each element which share the same class with the specified HWND. For example, in my case, the HWND is a Button element, and it's class is "Button", so all the buttons in my window will have the same cursor. How can I just change the cursor to a specified HWND? Something like this:

SetHwndCursor(hWindow, GCL_CURSOR, Cursor); //Invented function, just to make the example

Thanks.

2

2 Answers

4
votes

To show a different cursor than the class's default cursor, you need to handle the WM_SETCURSOR message for the window and call SetCursor in response to WM_SETCURSOR. For a brief example, see Displaying a Cursor.

You'll need to subclass the button to override the button's WndProc to handle WM_SETCURSOR. Use SetWindowSubclass to subclass the window (and then remove the subclassing with RemoveWindowSubclass when the button is destroyed, in response to WM_NCDESTROY—see Raymond Chen's Safer subclassing for details). SetWindowLongPtr is no longer recommended for subclassing windows.

Thanks to @IInspectable and @JonathanPotter for the information on SetWindowSubclass.

2
votes

I accomplish this by handling WM_SETCURSOR for the window in question and use SetCursor.