WPF and custom cursors

I want to set a custom cursor in my WPF application. I originally had a .png file that I converted to .ico, but since I couldn't find a way to set the .ico file as a cursor in WPF, I tried to do it with the appropriate .cur file.

I created such a .cur file using Visual Studio 2013 (New Item -> Cursor File). The cursor is a 24-bit color image and its assembly type is Resource.

I am requesting resource flow using this:

var myCur = Application.GetResourceStream(new Uri("pack://application:,,,/mycur.cur")).Stream;

      

This code is capable of fetching a stream, so myCur

it has no null value.

When trying to create a cursor with

var cursor = new System.Windows.Input.Cursor(myCur);

      

the default cursor is returned Cursors.None

, not my custom cursor. So there is a problem with this.

Can someone tell me why .ctor is having problems with my cursor thread? The file was generated using VS2013, so I assume the .cur file is formatted correctly. Alternatively: if anyone knows how to load the .ico file as a cursor in WPF, I would be very happy and very grateful.

EDIT: Just tried the same with a fresh new .cur file from VS2013 (8bpp), in case adding a new palette screwed up the image format. The same result. The System.Windows.Input.Cursor

.ctor cannot even create a correct cursor from a "fresh" cursor file.

+3


source to share


2 answers


Note: Possible tricking Custom Cursor in WPF?

Essentially you need to use the win32 method CreateIconIndirect



// FROM THE ABOVE LINK
public class CursorHelper
{
    private struct IconInfo
    {
        public bool fIcon;
        public int xHotspot;
        public int yHotspot;
        public IntPtr hbmMask;
        public IntPtr hbmColor;
    }

    [DllImport("user32.dll")]
    private static extern IntPtr CreateIconIndirect(ref IconInfo icon);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);


    public static Cursor CreateCursor(System.Drawing.Bitmap bmp, int xHotSpot, int yHotSpot)
    {
        IconInfo tmp = new IconInfo();
        GetIconInfo(bmp.GetHicon(), ref tmp);
        tmp.xHotspot = xHotSpot;
        tmp.yHotspot = yHotSpot;
        tmp.fIcon = false;

        IntPtr ptr = CreateIconIndirect(ref tmp);
        SafeFileHandle handle = new SafeFileHandle(ptr, true);
        return CursorInteropHelper.Create(handle);
    }
}

      

+3


source


This is exactly what I did and it seems to work fine. I just added this to the Pictures folder in my project in Visual Studio 2013. Maybe it can't resolve your URI?

    Cursor paintBrush = new Cursor(
        Application.GetResourceStream(new Uri("Images/paintbrush.cur", UriKind.Relative)).Stream
        );

      



Cursor example (worked for me): http://www.rw-designer.com/cursor-detail/67894

+2


source







All Articles