May 11, 2005

Loading Cursor From Win32 Resource File In .NET

See the my blog 'Creating a Win 32 Resource DLL' on how to create a C++ resource DLL Using Colored and Animated Cursors
Using legacy plug-ins with .NET - Using LoadLibrary,FreeLibrary and GetProcAdress within .NET to load and use legacy DLLs dynamically. Building Managed Resources from Win32 Resources Using Win32 and Other Libraries - Interop stuff Create Simple Load time DLLs
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

class Win32
 [DllImport("user32.dll", EntryPoint = "LoadCursorFromFileW", 
CharSet = CharSet.Unicode)] public static extern IntPtr LoadCursorFromFile(String str); [DllImport("user32.dll", EntryPoint = "LoadImageW",
CharSet = CharSet.Unicode)] public static extern IntPtr LoadImage(IntPtr hinst, string lpszName, uint uType, int cxDesired, int cyDesired, uint fuLoad); public const uint LR_LOADFROMFILE = 16; public const uint IMAGE_CURSOR = 2; } class CursorLoader { /// <summary> /// Load Coloured Cursor from a file. Do not scale the cursor to
the default size /// </summary> /// <param name="filename"></param> /// <returns></returns> public static Cursor LoadCursorFromFileUnscaled(string filename) { IntPtr hCursor; Cursor result = null; hCursor = Win32.LoadImage(IntPtr.Zero, filename, Win32.IMAGE_CURSOR,
0, 0, Win32.LR_LOADFROMFILE); if (!IntPtr.Zero.Equals(hCursor)) { result = new Cursor(hCursor); } else { throw new Exception("Could not create cursor from file "
+ filename); } return result; } }
To use the method
Cursor XxxCursor = CursorLoader.LoadCursorFromFileUnscaled("Xxx.cur");
This method can be adapted to load other resource types. Just play around with the Win32 'LoadImage' API call.

No comments: