WPF编程,自定义鼠标形状的一种方法。

时间:2023-02-09 16:46:17
原文: WPF编程,自定义鼠标形状的一种方法。

版权声明:我不生产代码,我只是代码的搬运工。 https://blog.csdn.net/qq_43307934/article/details/87275432

参考:https://www.cnblogs.com/TianFang/p/5186497.html

1、增加引用

System.Drawing.dll

2、代码

public class CursorHelper
    {
        static class NativeMethods
        {
            public struct IconInfo
            {
                public bool fIcon;
                public int xHotspot;
                public int yHotspot;
                public IntPtr hbmMask;
                public IntPtr hbmColor;
            }

            [DllImport("user32.dll")]
            public static extern SafeIconHandle CreateIconIndirect(ref IconInfo icon);

            [DllImport("user32.dll")]
            public static extern bool DestroyIcon(IntPtr hIcon);

            [DllImport("user32.dll")]
            [return: MarshalAs(UnmanagedType.Bool)]
            public static extern bool GetIconInfo(IntPtr hIcon, ref IconInfo pIconInfo);
        }

        [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
        class SafeIconHandle : SafeHandleZeroOrMinusOneIsInvalid
        {
            public SafeIconHandle()
                : base(true)
            {
            }

            protected override bool ReleaseHandle()
            {
                return NativeMethods.DestroyIcon(handle);
            }
        }

        static Cursor InternalCreateCursor(System.Drawing.Bitmap bitmap, int xHotSpot, int yHotSpot)
        {
            var iconInfo = new NativeMethods.IconInfo
            {
                xHotspot = xHotSpot,
                yHotspot = yHotSpot,
                fIcon = false
            };

            NativeMethods.GetIconInfo(bitmap.GetHicon(), ref iconInfo);

            var cursorHandle = NativeMethods.CreateIconIndirect(ref iconInfo);
            return CursorInteropHelper.Create(cursorHandle);
        }

        public static Cursor CreateCursor(UIElement element, int xHotSpot = 0, int yHotSpot = 0)
        {
            element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            element.Arrange(new Rect(new Point(), element.DesiredSize));

            var renderTargetBitmap = new RenderTargetBitmap(
                (int)element.DesiredSize.Width, (int)element.DesiredSize.Height,
                96, 96, PixelFormats.Pbgra32);

            renderTargetBitmap.Render(element);

            var encoder = new PngBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));

            using (var memoryStream = new MemoryStream())
            {
                encoder.Save(memoryStream);
                using (var bitmap = new System.Drawing.Bitmap(memoryStream))
                {
                    return InternalCreateCursor(bitmap, xHotSpot, yHotSpot);
                }
            }
        }
    }

3、调用

this.Cursor = CursorHelper.CreateCursor(elips);//elips是自定义控件的名字