How to load an embedded cursor from resources – one that has 32-bit colour, is a trick that has eluded me for a long time, until now.
Wait. What’s that, you say? The managed Cursor type does not support animated cursors (.ani files) or cursors with colours other than black and white. Shut up! Fuck… Yes, and this is why I have never asked the question on StackOverflow. Ten thousand copy-and-paste programmers will be sure to tell me it can’t be done.
If you have more than a couple of brain cells and you actually think about it, it should be obvious that this can be done, in much the same way as you can load a custom icon from an unmanaged native icon handle. The real question is, which Windows API function is the appropriate one to call? I tried all the documented Cursor functions in the MSDN documentation a long time ago, and to my dismay, none of them solved this problem. Thus for a long time, I used an annoying hack to work around it: Create temporary files from my resource cursors, then read them using the LoadCursorFromFile API function. Obviously this function should not be necessary, but I figured at least it works, and it shows that creating a managed Cursor instance from an unmanaged Cursor handle does work and that one day I will find the correct function to use when reading it from resources instead. That day is today.
Quite by accident I stumbled on the correct function: CreateIconFromResource, which can load icons or cursors. I couldn’t find it before because of the function’s name, and it is neither grouped with, nor linked to the cursor functions in the documentation.
So here’s the code. This is based on an example at the pinvoke.net page for CreateIconFromResource, except that the original author omitted to destroy the native cursor handle. (It’s one of my pet peeves. In almost every code sample I find online, the author either omits freeing up some memory for something when it is clearly documented as a requirement, or they implement IDisposable incorrectly.)
Using this code is as easy as adding the cursor to your application resources, then load it with something along the lines of:
handUpCursor = CursorResourceLoader.LoadEmbeddedCursor(Properties.Resources.Hand_up);