code_junkie

Custom cursor in WPF?

Nov 10th, 2011
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. <Window.Resources>
  2. <ResourceDictionary>
  3. <TextBlock x:Key="CursorGrab" Cursor="Resources/Cursors/grab.cur"/>
  4. <TextBlock x:Key="CursorMagnify" Cursor="Resources/Cursors/magnify.cur"/>
  5. </ResourceDictionary>
  6. </Window.Resources>
  7.  
  8. if (selectedTool == "Hand")
  9. myCanvas.Cursor = ((TextBlock)this.Resources["CursorGrab"]).Cursor;
  10. else if (selectedTool == "Magnify")
  11. myCanvas.Cursor = ((TextBlock)this.Resources["CursorMagnify"]).Cursor;
  12. else
  13. myCanvas.Cursor = Cursor.Arrow;
  14.  
  15. public Cursor ConvertToCursor(Visual visual, Point hotSpot)
  16. {
  17. int width = (int)visual.Width;
  18. int height = (int)visual.Height;
  19.  
  20. // Render to a bitmap
  21. var bitmapSource = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
  22. resultSource.Render(visual);
  23.  
  24. // Convert to System.Drawing.Bitmap
  25. var pixels = new int[width*height];
  26. bitmapSource.CopyPixels(pixels, width, 0);
  27. var bitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppPargb);
  28. for(int y=0; y<height; y++)
  29. for(int x=0; x<width; x++)
  30. bitmap.SetPixel(x, y, Color.FromArgb(pixels[y*width+x]));
  31.  
  32. // Save to .ico format
  33. var stream = new MemoryStream();
  34. new System.Drawing.Icon(resultBitmap.GetHIcon()).Save(stream);
  35.  
  36. // Convert saved file into .cur format
  37. stream.Seek(2);
  38. stream.Write(2);
  39. stream.Seek(10);
  40. stream.Write((byte)(int)(hotSpot.X * width);
  41. stream.Write((byte)(int)(hotSpot.Y * height);
  42. stream.Seek(0);
  43.  
  44. // Construct Cursor
  45. return new Cursor(stream);
  46. }
  47.  
  48. <Grid x:Name="customCursor" Width="32" Height="32">
  49. ...
  50. </Grid>
  51.  
  52. someControl.Cursor = ConvertToCursor(customCursor, new Point(0.5, 0.5));
  53.  
  54. <Window Cursor=""C:WINDOWSCursorsdinosaur.ani"" />
Add Comment
Please, Sign In to add comment