Custom cursor in WPF?

2019-01-03 05:31发布

I want to use an image or icon as a custom cursor in WPF app. What's the best way to do it?

15条回答
Summer. ? 凉城
2楼-- · 2019-01-03 05:56

Like Peter mentioned above, if you already have a .cur file, you can use it as an embedded resource by creating a dummy element in the resource section, and then referencing the dummy's cursor when you need it.

For example, say you wanted to display non-standard cursors depending on the selected tool.

Add to resources:

<Window.Resources>
    <ResourceDictionary>
        <TextBlock x:Key="CursorGrab" Cursor="Resources/Cursors/grab.cur"/>
        <TextBlock x:Key="CursorMagnify" Cursor="Resources/Cursors/magnify.cur"/>
    </ResourceDictionary>
</Window.Resources>

Example of embedded cursor referenced in code:

if (selectedTool == "Hand")
    myCanvas.Cursor = ((TextBlock)this.Resources["CursorGrab"]).Cursor;
else if (selectedTool == "Magnify")
    myCanvas.Cursor = ((TextBlock)this.Resources["CursorMagnify"]).Cursor;
else
    myCanvas.Cursor = Cursor.Arrow;

-Ben

查看更多
女痞
3楼-- · 2019-01-03 05:56

A very easy way is to create the cursor within Visual Studio as a .cur file, and then add that to the projects Resources.

Then just add the following code when you want to assign the cursor:

myCanvas.Cursor = new Cursor(new System.IO.MemoryStream(myNamespace.Properties.Resources.Cursor1));
查看更多
家丑人穷心不美
4楼-- · 2019-01-03 05:56

Also check out Scott Hanselman's BabySmash (www.codeplex.com/babysmash). He used a more "brute force" method of hiding the windows cursor and showing his new cursor on a canvas and then moving the cursor to were the "real" cursor would have been

Read more here: http://www.hanselman.com/blog/DeveloperDesigner.aspx

查看更多
等我变得足够好
5楼-- · 2019-01-03 05:58

It may have changed with Visual Studio 2017 but I was able to reference a .cur file as an embedded resource:

<Setter
    Property="Cursor"
    Value="/assembly-name;component/location-name/curser-name.cur" />
查看更多
来,给爷笑一个
6楼-- · 2019-01-03 06:01

To use a custom cursor in XAML I altered the code Ben McIntosh provided slightly:

<Window.Resources>    
 <Cursor x:Key="OpenHandCursor">Resources/openhand.cur</Cursor>
</Window.Resources>

To use the cursor just reference to the resource:

<StackPanel Cursor="{StaticResource OpenHandCursor}" />
查看更多
小情绪 Triste *
7楼-- · 2019-01-03 06:06

You could try this

<Window Cursor=""C:\WINDOWS\Cursors\dinosaur.ani"" />
查看更多
登录 后发表回答