Loading

WPF鼠标形状的设置

1、使用 Cursor属性设置鼠标形状

<Button Cursor="Hand" />

鼠标形状的枚举数值如下所示:

public enum CursorType
{
    None = 0,
    No = 1,
    Arrow = 2,
    AppStarting = 3,
    Cross = 4,
    Help = 5,
    IBeam = 6,
    SizeAll = 7,
    SizeNESW = 8,
    SizeNS = 9,
    SizeNWSE = 10,
    SizeWE = 11,
    UpArrow = 12,
    Wait = 13,
    Hand = 14,
    Pen = 15,
    ScrollNS = 16,
    ScrollWE = 17,
    ScrollAll = 18,
    ScrollN = 19,
    ScrollS = 20,
    ScrollW = 21,
    ScrollE = 22,
    ScrollNW = 23,
    ScrollNE = 24,
    ScrollSW = 25,
    ScrollSE = 26,
    ArrowCD = 27
}

2、加载外部图片作为鼠标形状

public class CursorSafeHandle : SafeHandle
{
    public CursorSafeHandle(IntPtr preexistingHandle, bool ownsHandle)
        : base(IntPtr.Zero, ownsHandle)
    {
        handle = preexistingHandle;
    }
    public override bool IsInvalid
    {
        get { return handle == IntPtr.Zero; }
    }
    protected override bool ReleaseHandle()
    {
        return true;
    }
}
Bitmap dimage = new Bitmap("update.png");
var handle = dimage.GetHicon();
var c = new CursorSafeHandle(handle, true);
var cursor= CursorInteropHelper.Create(c);
testButton.Cursor = cursor;

3、创建Bitmap图像

我们还可以在GDI+上绘制图形作为鼠标形状:

private Bitmap FillGraphToBitmap()
{
    var backBitmap = new Bitmap(20, 20);
    using (Graphics graphics = Graphics.FromImage(backBitmap))
    {
        // 设置背景色
        graphics.Clear(System.Drawing.Color.Transparent);
        // 绘制圆
        Brush greenBrush = new SolidBrush(Color.Green);
        graphics.FillEllipse(greenBrush, 0, 0, backBitmap.Width, backBitmap.Height);
        graphics.Dispose();
    }
    return backBitmap;
}
posted @ 2023-06-02 10:06  Dwaynerbing  阅读(1282)  评论(0编辑  收藏  举报