0

From the answer provided here Can I choose a custom image for C# Windows Application Drag Drop functions?, why does the following line:

return new Cursor(CreateIconIndirect(ref tmp));

cause the compiler to emit this error:

The best overloaded method match for 'System.Windows.Input.Cursor.Cursor(string)' has some invalid arguments Argument 1: cannot convert from 'System.IntPtr' to 'System.Runtime.InteropService.SafeHandle'

and is there a way to fix it?

Community
  • 1
  • 1
4thSpace
  • 43,672
  • 97
  • 296
  • 475
  • That code can only work in a Winforms project. You don't want to use it anyway, it has a nasty handle leak that will crash your program after a while. – Hans Passant Aug 02 '16 at 08:14

1 Answers1

1

The basic issue here is that you are trying to use a code example meant for the Winforms API when you are actually using the WPF API. The Cursor class used in that code is System.Windows.Forms.Cursor, while the class you're using is actually System.Windows.Input.Cursor. They are completely different, including having completely different constructors.

The Winforms version will accept an IntPtr value, representing a handle to a native Windows cursor object. But the WPF class accepts only some existing .cur or .ani data, either via a Stream (the data itself) or a string instance (the name of a file…this can be a pack: scheme path, so you can use embedded resources if you like).

If you want to create a cursor from an image on the fly in WPF, you can either:

  1. Use the Winforms example but instead of trying to pass the cursor handle to the Cursor constructor, use additional native functions via interop to retrieve the cursor data, write it to an array, and then wrap the array in a MemoryStream that you can pass to the WPF Cursor constructor. Or,
  2. Use one of the WPF-specific solutions for creating a Cursor object from existing image data. For example, Custom cursor in WPF? (I particularly like this answer…there are several good ones there, though they all involve using GDI+ via the System.Drawing namespace at some point), or Rotating Cursor According to Rotated TextBox (again, uses GDI+).
Community
  • 1
  • 1
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136