5

I have a System.Windows.Forms.Cursor with me and wanted to assign it to a WPF's image.Cursor property which happens to be of System.Windows.Input.Cursor type. The constraint here is, the former Cursor type is returned by our Framework and i can in no way modify it. Is there any way of casting the former to latter?

3
  • 1
    I browsed few sites in search of the answer before posting here. But with less luck...[:(] Commented Aug 9, 2011 at 3:18
  • I doubt you can cast it. You'd probably have more luck converting its image. Commented Aug 9, 2011 at 3:45
  • You can't just cast it, but you might be able to stream the cursor data out to a file or memory stream from the underlying Cursor.Handle. You could then pass this into the WPF Cursor(Stream) constructor. Saving a cursor given its handle will involve dropping down to the Windows API and even then seems terribly badly documented, but codeguru.com/forum/showthread.php?t=353956 has a few suggestions. Commented Aug 9, 2011 at 4:58

2 Answers 2

5

This did the trick for me:

SafeFileHandle panHandle = new SafeFileHandle(System.Windows.Forms.Cursors.PanNorth.Handle, false);
this.Cursor = System.Windows.Interop.CursorInteropHelper.Create(panHandle);

Documentation for SafeFileHandle warns against using false for the second arg but I got SEHExceptions no matter what if I used true (even if I used Cursors.PanNorth.CopyHandle())

Sign up to request clarification or add additional context in comments.

2 Comments

Excellent, +1. Should note for anyone seeing this - System.Windows.Forms.Cursors.PanNorth was hard-coded in -- you can send in any System.Windows.Forms.Cursor and get its .Handle and it will work - even a custom one defined with Bitmap bmp = Bitmap.FromFile(filePath); IntPtr ptr = bmp.GetHicon(); System.Windows.Forms.Cursor c = new System.Windows.Forms.Cursor(ptr);. So then you just put in c.Handle instead of the System.Windows.Forms.Cursors.PanNorth.Handle.
I combined this with a caching scheme - I suspect if you just convert the Cursors as needed without disposing them you'll end up with a resource leak.
2

I avoided SEHExceptions by this:

this.panHandle?.Close();
this.panHandle = new SafeFileHandle(System.Windows.Forms.Cursors.PanNorth.Handle, false);
this.Cursor = System.Windows.Interop.CursorInteropHelper.Create(panHandle);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.