Monday, February 13, 2012

Custom cursor in WPF

I want to show one of my toolbar icon image as cursor when user clicks on the toolbar icon...as we can achieve same in winforms very easier but in WPF cursor object is defined in System.Windows.Input.Cursor instead of System.Windows.Forms.Cursor with restricted the constructor parameters to avoid old GDI objects.

 I have spent almost 2 to 3 hours searching in internet and finally got an way to achieve the same. so i want share with so that it will save some of you valuable hours.

Below is the exact code

 IntPtr curPtr = Properties.Resources.moveMode.GetHicon();
            Microsoft.Win32.SafeHandles.SafeFileHandle handle = new Microsoft.Win32.SafeHandles.SafeFileHandle(curPtr, true);           
DrawingSurface.Cursor = System.Windows.Interop.CursorInteropHelper.Create(handle);

Properties.Resources.moveMode - Bitmap icon from my project resource file which i have used in toolbar icon so want to use the same icon for cursor also.

Rest of the code can be easily understandable we have to use the SafeFileHandle which is used to represents a wrapper class for a file handle and Interop CursorInteropHelper class to convery the bitmap handle into cursor...it's definition defined in MSDN below.

"Provides a static helper class for WPF/Win32 interoperation with one method, which is used to obtain a Windows Presentation Foundation (WPF) Cursor object based on a provided Win32 cursor handle."