2015-01-01 41 views
2

我想在我的WPF应用程序中设置自定义游标。最初我有一个.png文件,我转换为.ico,但由于我没有找到任何方式将WPF文件设置为光标,我试图用正确的.cur文件来做到这一点。WPF和自定义游标

我已经使用Visual Studio 2013(New Item - > Cursor File)创建了这样一个.cur文件。游标是一个彩色的24位图像,其构建类型是“资源”。

我accquire资源流与此:

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

这个代码能够检索流,所以myCur空aferwards。

当试图与

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

默认光标Cursors.None创建光标返回,而不是我定义光标。所以似乎有一个问题。

有人能告诉我为什么.ctor与我的光标流有问题吗?该文件是使用VS2013本身创建的,因此我假定.cur文件格式正确。或者:如果有人知道如何将一个.ico文件作为游标加载到WPF中,我会非常高兴和非常感激。

编辑:刚刚尝试过,从VS2013(8bpp)新鲜的新.cur文件,以防万一添加一个新的调色板拧紧了图像格式。同样的结果。 System.Windows.Input.Cursor的.ctor甚至不能从“新鲜”光标文件创建适当的光标。

回答

3

注:Custom cursor in WPF?

可能的欺骗本质,你必须使用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); 
    } 
} 
+0

我会诅咒,就像一个魅力。我_did_做一些谷歌搜索,不知道为什么我没有打你发布的链接:/非常感谢 - 接受的答案。 – PuerNoctis

+0

包装的结果CreateIconIndirect将导致SafeFileHandle GC'ed异常 - 请参阅http://stackoverflow.com/questions/9218029/safefilehandle-close-throws-an-exception-but-the-handle-is-有效-和作品 – user3391859

1

这正是我所做的,它似乎是工作的罚款。我只是将它添加到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