Using a Windows.Forms.Cursor for a WPF Cursor?
Asked Answered
P

2

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?

Paries answered 9/8, 2011 at 3:17 Comment(3)
I browsed few sites in search of the answer before posting here. But with less luck...[:(]Paries
I doubt you can cast it. You'd probably have more luck converting its image.Garv
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.Equally
E
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())

Exalted answered 18/10, 2012 at 16:58 Comment(2)
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.Ruddie
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.Tillotson
B
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);
Billiot answered 16/3, 2022 at 19:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.