WPF和自定义光标

4
我希望在我的WPF应用程序中设置自定义光标。最初,我有一个.png文件,我将其转换为.ico文件,但由于我没有找到在WPF中设置.ico文件作为光标的方法,因此我尝试使用正确的.cur文件来实现这一点。
我使用Visual Studio 2013(New Item-> Cursor File)创建了这样一个.cur文件。该光标是一个彩色的24位图像,其构建类型为“资源”。
我使用以下代码获取资源流:
var myCur = Application.GetResourceStream(new Uri("pack://application:,,,/mycur.cur")).Stream;

这段代码可以检索流,因此在此之后myCur不是空的。
尝试创建游标时:
var cursor = new System.Windows.Input.Cursor(myCur);

默认光标Cursors.None被返回而不是我的自定义光标。看起来有问题。
请问有人能告诉我为什么ctor无法处理我的光标流吗?该文件是使用VS2013创建的,因此我认为.cur文件格式正确。或者:如果有人知道如何将.ico文件加载为WPF中的光标,我将非常高兴和感激。
编辑:尝试使用来自VS2013的全新.cur文件(8bpp),以防添加新调色板会破坏图像格式。结果相同。System.Windows.Input.Cursor的.ctor甚至无法从“fresh”光标文件创建适当的光标。
2个回答

3

本质上你需要使用win32方法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);
    }
}

1
当 SafeFileHandle 被垃圾回收时,包装 CreateIconIndirect 的结果会导致异常 - 请参阅 https://dev59.com/oGDVa4cB1Zd3GeqPbkFs - user3391859

3

我完全按照这样做,似乎运行良好。 我只是在Visual Studio 2013项目下的“Images”文件夹中添加了这个。也许它无法解析您的URI?

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

示例光标(适用于我):http://www.rw-designer.com/cursor-detail/67894

意思是:这是一个示例光标,可以在链接中找到。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接