3

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.

Barmak Shemirani
  • 30,904
  • 6
  • 40
  • 77
ProtectedVoid
  • 1,293
  • 3
  • 17
  • 42

2 Answers2

4

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.

Lithis
  • 1,327
  • 8
  • 14
  • 2
    [Subclassing Controls](https://msdn.microsoft.com/en-us/library/windows/desktop/bb773183.aspx) describes the disadvantages of using the old subclassing approach (`SetWindowLongPtr`), and explains the proper way. – IInspectable Jul 09 '15 at 14:48
  • 1
    All modern systems have comctl32.dll version 6. No one should be writing programs to target Windows 98 any more. And `SetWindowSubclass` was added in 5.8 anyway. – Jonathan Potter Jul 09 '15 at 21:20
2

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

mark
  • 5,269
  • 2
  • 21
  • 34
  • 1
    SetCursor changes the global cursor, not applied natively to a certain element, am i wrong? Thanks. – ProtectedVoid Jul 09 '15 at 14:38
  • As soon as the mouse moves, the window it's over can/will set it to what it wants... including windows that your application doesn't own. In effect, it applies only to a certain element. – mark Jul 09 '15 at 15:47