自定义Cursor

http://stackoverflow.com/questions/46805/custom-cursor-in-wpf

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;

public Cursor ConvertToCursor(Visual visual, Point hotSpot) {   int width = (int)visual.Width;   int height = (int)visual.Height;    // Render to a bitmap   var bitmapSource = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);   resultSource.Render(visual);    // Convert to System.Drawing.Bitmap   var pixels = new int[width*height];   bitmapSource.CopyPixels(pixels, width, 0);   var bitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppPargb);   for(int y=0; y<height; y++)     for(int x=0; x<width; x++)       bitmap.SetPixel(x, y, Color.FromArgb(pixels[y*width+x]));    // Save to .ico format   var stream = new MemoryStream();   new System.Drawing.Icon(resultBitmap.GetHIcon()).Save(stream);    // Convert saved file into .cur format   stream.Seek(2);   stream.Write(2);   stream.Seek(10);   stream.Write((byte)(int)(hotSpot.X * width);   stream.Write((byte)(int)(hotSpot.Y * height);   stream.Seek(0);    // Construct Cursor   return new Cursor(stream); } Note that your Visual's size must be a standard cursor size (eg 16x16 or 32x32), for example:

<Grid x:Name="customCursor" Width="32" Height="32">   ... </Grid> It would be used like this:

someControl.Cursor = ConvertToCursor(customCursor, new Point(0.5, 0.5)); Obviously your Visual could be an <Image> control if you have an existing image, or you can draw anything you like using WPF's built-in drawing tools.

Note that details on the .cur file format can be found at ICO (file format).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值