/// <summary> /// Create cursor from canvas. /// </summary> /// <param name="canvas">Input canvas.</param> /// <param name="hotSpotPoint">Hotspot cursor point.</param> /// <returns>Created cursor.</returns> private System.Windows.Forms.Cursor _CreateCursorFromCanvas(Canvas canvas, System.Drawing.Point hotSpotPoint) { // Render canvas to bitmap. RenderTargetBitmap targetBitmap = new RenderTargetBitmap((int)canvas.ActualWidth, (int)canvas.ActualHeight, BASIC_DPI, BASIC_DPI, PixelFormats.Pbgra32); targetBitmap.Render(canvas); // Create PNG encoder. PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(targetBitmap)); // Render target bitmap to System.Drawing bitmap. System.Drawing.Bitmap bmp; using (MemoryStream stream = new MemoryStream()) { encoder.Save(stream); bmp = new System.Drawing.Bitmap(stream); } // Create cursor. WinAPIHelpers.IconInfo iconInfo = new WinAPIHelpers.IconInfo(); IntPtr hIcon = bmp.GetHicon(); WinAPIHelpers.GetIconInfo(hIcon, ref iconInfo); iconInfo.xHotspot = hotSpotPoint.X; iconInfo.yHotspot = hotSpotPoint.Y; iconInfo.fIcon = false; IntPtr cursorHandle = WinAPIHelpers.CreateIconIndirect(ref iconInfo); // Destroy icon obtained from GetHicon method. if (hIcon != IntPtr.Zero) { WinAPIHelpers.DestroyIcon(hIcon); } // Free resources. if (iconInfo.hbmColor != IntPtr.Zero) { WinAPIHelpers.DeleteObject(iconInfo.hbmColor); } if (iconInfo.hbmMask != IntPtr.Zero) { WinAPIHelpers.DeleteObject(iconInfo.hbmMask); } System.Windows.Forms.Cursor cursor = null; if (cursorHandle != null) { cursor = new System.Windows.Forms.Cursor(cursorHandle); } return(cursor); }
/// <summary> /// Creates image from input cursor for adding to WPF canvas. /// </summary> /// <param name="cursor">Cursor to convert.</param> /// <param name="hotSpot">Output cursor hotspot point.</param> /// <returns>Create cursor image.</returns> private Image _CreateImageFromCursor(System.Windows.Forms.Cursor cursor, out System.Drawing.Point hotSpot) { // Get info about cursor. WinAPIHelpers.IconInfo iconInfo = new WinAPIHelpers.IconInfo(); if (WinAPIHelpers.GetIconInfo(cursor.Handle, ref iconInfo)) { // Set hotspot point. hotSpot = new System.Drawing.Point { X = iconInfo.xHotspot, Y = iconInfo.yHotspot }; // Free bitmap objects. if (iconInfo.hbmColor != IntPtr.Zero) { WinAPIHelpers.DeleteObject(iconInfo.hbmColor); } if (iconInfo.hbmMask != IntPtr.Zero) { WinAPIHelpers.DeleteObject(iconInfo.hbmMask); } } else { // We didn't get info about cursor for some reason - set hot spot to (0; 0). hotSpot = new System.Drawing.Point { X = 0, Y = 0 }; } // Create bitmap source from cursor (cursor handle is icon handle as well). BitmapSource source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHIcon(cursor.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); // Create image control. Image image = new Image(); image.Source = source; return(image); }