WPF编程,自定义鼠标形状的一种方法。
程序员文章站
2022-06-07 15:13:49
...
参考: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是自定义控件的名字
上一篇: WPF采用MVVM模式命令绑定
下一篇: wpf-基础-命令-命令参数