6
votes

The Problem

On windows, the coordinates returned for a "mouse button down" event seem to be slightly wrong for an I-Beam cursor. Basically, the x-coordinate is always two pixels left of where it should be.

I've written a very simple win32 program to demonstrate the problem. All it does is turn the cursor into an IBeam and render a vertical red line where the last mouse down event was. I would expect the red line to match up exactly with the vertical part of the I-Beam, but this is not the case.

Here's a screenshot of what happens.

As you can see, the red line is two pixels to the left of where it should be (the behaviour is correct for the standard arrow pointer), so it appears that the hotspot for the I-Beam cursor is wrong.

I've had someone else running Windows 7 64 bit confirm that they experience the same problem, but another tester on Vista does not have the problem.


Some information about my environment

  • Windows 7 64 bit. Completely default configuration (i.e. no DPI scaling, no weird themes etc)
  • Visual Studio Express 2010
  • NVidia graphics card with latest drivers (v270.61)
  • Switching aero on or off makes no difference. Choosing different cursors in display preferences makes no difference

The Relevant Bits Of Code

My test project is basically the "Win32 Project" template in Visual C++ 2010, with the changes outlined below.

Here's the code where I register the window class and set the cursor to an I Beam

ATOM MyRegisterClass(HINSTANCE hInstance)
{
    WNDCLASSEX wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);

    wcex.style          = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = WndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_CURSOR_TEST));
    wcex.hCursor        = LoadCursor(NULL, IDC_IBEAM); // this is the only line I changed in this function
    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName   = MAKEINTRESOURCE(IDC_CURSOR_TEST);
    wcex.lpszClassName  = szWindowClass;
    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));

    return RegisterClassEx(&wcex);
}

Here are the relevant parts from my main message loop:

case WM_LBUTTONDOWN:
    // record position of mouse down. 
    // xPos and yPos are just declared as
    // global ints for the purpose of this test
    xPos = GET_X_LPARAM(lParam); 
    yPos = GET_Y_LPARAM(lParam);
    // cause redraw
    InvalidateRect(hWnd, NULL, TRUE);
    UpdateWindow(hWnd);
    break;      

case WM_PAINT:
    // paint vertical red line at position of last click
    hdc = BeginPaint(hWnd, &ps);
    RECT rcClient;
    GetClientRect(hWnd, &rcClient);
    hPen = CreatePen(PS_SOLID, 1, RGB(255, 0, 0));
    SelectObject(hdc, hPen);
    MoveToEx(hdc, xPos, 0, NULL);
    LineTo(hdc, xPos, rcClient.bottom);
    DeleteObject(hPen);
    EndPaint(hWnd, &ps);
    break;

The Summary

I've done loads of googling for answers, but can't find anything relevant. Am I doing something wrong with the way that I'm handling the incoming cursor coordinates?

Thanks!


EDIT: More Information After Insightful Questions in the Comments

As guided by @Mark Ransom in the comments, I've used the GetIconInfo function to get more information about the I-Beam cursor. The ICONINFO struct for the cursor indicates that the x coord for the cursor hotspot is at x=8. However, when I dump the bitmap for the cursor (the hbmMask member of the ICONINFO struct, as it is a monochrome cursor), the vertical bar is 10 pixels from the left of the image, not 8 pixels. As Mark points out this is likely the cause of the visual discrepency, but why has this occurred, and how might I fix it?

(I also noticed that the answer to this other question has some interesting information about the different way that I-Beam cursors are handled. I wonder if this is relevant)

1
You can use GetIconInfo to get the hotspot coordinates, it would shed some light on the problem.Mark Ransom
Hi @Mark-Ransom. GetIconInfo tells me that the hotspot for the IDC_IBEAM pointer is xHotspot==8 yHotspot==9. (For reference, that function tells me that the hotspot for the standard IDC_ARROW pointer is xHotspot==0 yHotspot==0). Is there something further I can derive from this information? Thanks.Gerald6502
The click point should be at the hotspot coordinates relative to the top-left corner of the cursor image. If you can dump the cursor bitmap and examine it, the vertical bar should also be 8 pixels from the left side. If it's not, there's your problem.Mark Ransom
Ok, I've dumped the cursor bitmap (well, actually I've dumped the the hbmMask bitmap from the ICONINFO struct returned by GetIconInfo. The hbmColor bitmap isn't set, because the I-Beam is a monochrome cursor). The result is that the vertical bar is 10 pixels from the left side, not the 8 pixels indicated by the xHotspot member. As @Mark points out, this is clearly wrong, but I'm completely lost as to how this conflicting information is present in the structure and how I might go about fixing it.Gerald6502
I can see why that would work, but it's more of a workaround. Surely I'm either (a) doing something wrong or (b) the hotspot of the built-in I-Beam cursors is inaccurate for all users of Windows 7? In other words, I'd prefer to try and find the root cause of the problem before resorting to workarounds. I hope this seems reasonable ;)Gerald6502

1 Answers

1
votes

This was plaguing me for many years, and evidently many other Windows users? Do you ever just click between two characters, but the text caret ends up too far to the left? Your cursor was clearly between the other two!

If you open Notepad, and then move your cursor to the bottom edge, out of the text region, and observe the change between I-beam and pointer, you can see that the pointer begins two pixels to the left of the I-beam. OP has thoroughly observed this by even writing a program to test just where that misbehaved I-beam cursor is clicking. It must be that the hotspot is set incorrectly. (Never imagined I’d be one of those people who take screenshots with their phone, but in this case, it was actually the easiest method I had in mind to capture the mouse cursor.)

I-beam misaligned with cursor I-beam misaligned with cursor

All right, so how do we fix it? Well, any sane Windows user would open their Mouse settings in the Control Panel, and then very simply change the I-beam cursor to a different version that has a correct hotspot. I could’ve sworn that I’ve done this before, having downloaded a corrected I-beam cursor (that looked just the same) from somewhere, but I can’t seem to find the link where I got it from – but yes, this approach will most assuredly give you a correct hotspot for text selection.

Would it truly fix the problem, though? Or would it leave you sleepless, wondering – knowing – you covered it up...

Doesn’t seem so hard to really fix, anyway...right? We’ll just go and adjust the original cursor file. So, I open Mouse settings in the Control Panel, and then click Browse..., search through the list in Windows/Cursors, but... it’s not there? I looked twice, and then thrice – definitely missing. There weren’t any that resembled what I was using.

Not my I-beam

So, I peer into the Windows Registry via regedit – I figured that I could find the file path to it in there. It was simple enough to find where the keys were via Google: HKEY_CURRENT_USER/Control Panel/Cursors. But wait – it’s not there either?! I see Arrow, Hand, and other cursors, but no “Ibeam” or “TextSelection” entry anywhere!

Regedit

You smart people are probably laughing at my bewilderment, knowing fully just where Windows keeps its secret cursors, but alas, my ignorance tormented me. I continued to dig fruitlessly through the other keys trying to find it – maybe text selection was special and had cursor information elsewhere under a related key?

Soon I came to the reasonable assumption that Windows uses a default cursor file if the key isn’t set – but where would that be? Fortunately, I have a modicum of Windows programming experience and know that things can come from embedded resources rather than a standalone .cur file. With some deeper digging, someone named Herby had the answer for me:

They are located in user32.dll [%WinDir%/system32].

(via https://www.neowin.net/forum/topic/374461-default-xp-cursor-location/)

Light at the end of the tunnel. I already had Resource Hacker installed on my computer for some reason, probably because I was doing something deranged before, but I peered inside user32.dll and, sure enough, found the default cursor resources. There was the I-beam under resource ID 73.

Resource Hacker

I exported it and had a look with a hex editor while referencing the ICO file format. Byte offset 10 has the horizontal pixel coordinate of the hotspot, which was 8. I could just change that byte from 0x08 to 0x0A and then import the modified file back into user32.dll with Resource Hacker, and my problem would be solved (permission issues aside).

Easy!

That’s simple enough, but do we really want simple? We’ve come this far, so may as well waste the rest of our day. Let’s write a C++ program to do it! Of course, being the totally good engineers we are, we must find a method to do this safe and proper...

Thus began my journey into the deepest depths of programmer hell, suffering the documents of yore which describe obscure WinAPI methods, like those pertaining to updating a DLL resource. First big obstacle here was that magic number, the ID of the cursor resource we want to modify, “73.” What did it mean? Where did it come from?

Well, to me it’s obvious that it’s a generated ID and can’t be trusted to be the de-facto constant that represents the I-beam cursor. So, we need to find some way to find that magic number reliably. Seems simple on paper, no? Well, it isn’t.

Closest I had gotten to tracking down the elusive magic number was the string “USER32” identifying the module, from GetIconInfoEx. Nothing that was actually useful. (Oh, and by the way, fair warning to anyone who wants to figure out .cur files and their butchered BMP format.) If you can find a way to turn IDC_IBEAM into a key name in the user32.dll resources, hats off to you, but after slamming my head against the wall for the better part of this project I decided to go with a dumber approach.

I just copied the original data, exporting it directly from the cursor resource to be used as a signature. I could then LoadLibrary user32.dll, enumerate through the cursors, and then check if they exactly match the signature file. If I find a match, I’ve found the ID I want to modify. I also learned that the second magic number I saw in Resource Hacker was a language code – “1033” (English US). I had to annoyingly do another enumeration to find that number, too.

All’s well and good, several hours later from digging through documentation, I have my solution. There are functions in the Windows API to update resources in DLL files. All I had to do was change the first byte of the signature file (which was the horizontal hotspot offset), and update the resource.

With permission, of course

It was about halfway through this project that I reminded myself it’s a horrible idea to modify system files (especially if it makes the system think something is wrong/out-of-date), let alone what measures the system will take to try and stop you from doing that, but I just couldn’t live without the sweet satisfaction knowing that I completed the solution. And it did work – I made a copy of user32.dll, ran the code, and sure enough, the cursor hotspot was corrected.

RESULT: https://github.com/mukunda-/IBeamFix

System files are system files though, and not even with Administrator access will the system let you mess with them. I’m not going to bother with figuring out how to circumvent that.

A better approach may have been to simply (and by simply, I mean dealing with CUR/BMP hell) export the cursor from user32.dll, checking its characteristics to make sure that it still has the hotspot flaw, modifying the hotspot coordinate, and then updating the registry to use that cursor.

Or, even better, not even bothering with any of this utter madness and just using a replacement cursor. I should have stopped at paragraph four. Look, I made one. https://mukunda.com/stuff/IBeamFixed.cur Problem solved.