C#、WPF中如何自定义鼠标样式

需求:在C#中如何自定义鼠标样式?在这里可以分两种情况,一种是在winForm,另一种是在WPF中(注意使用的Cursor对象不一样)

解决办法如下:

a.首先针对WinForm中,我们可以采用图标加载方式,代码如下:(这种情况用在普通控件上,但在MouseMove事件中使用,移动时鼠标会一直跳动)

public void SetCursor(System.Drawing.Bitmap cursor)

{

    try

    {

        System.Drawing.Bitmap newCursor = new System.Drawing.Bitmap(cursor.Width, cursor.Height); ;

        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(newCursor);

        g.Clear(System.Drawing.Color.FromArgb(0, 0, 0, 0));

 

        g.DrawImage(cursor, 0, 0, cursor.Width, cursor.Height);

        System.Windows.Forms.Cursor.Current = new System.Windows.Forms.Cursor(newCursor.GetHicon());

        g.Dispose();

        newCursor.Dispose();

    }

    catch (Exception)

    {

        return;

    }

}

b.针WPF中,它使用的鼠标对象为Cursor对象,而Cursor实例中有只有Stream与.ani、.cur文件等,而这类的文件又不要创建,没有直接使用图标引用来的快,下面这种方法就可以直接使用图标来引用(并且移动鼠标时,也不会有跳动现象,,但这里需要提醒下,网上有种类似的方法,它未继承SafeHandle类,导致使用时会产生内存泄漏问题,请谨慎使用)

internal class BitmapCursor:System.Runtime.InteropServices.SafeHandle

{

public override bool IsInvalid

{

get { return handle == (IntPtr)(-1); }

}

public static Cursor CreateBmpCursor(System.Drawing.Bitmap cursorBitmap)

{

var c = new BitmapCursor(cursorBitmap);

return System.Windows.Interop.CursorInteropHelper.Create(c);

}

protected BitmapCursor(System.Drawing.Bitmap cursorBitmap)

:base((IntPtr)(-1),true)

{

handle = cursorBitmap.GetHicon();

}

protected override bool ReleaseHandle()

{

bool result = DestroyIcon(handle);

handle = (IntPtr)(-1);

return result;

}

[System.Runtime.InteropServices.DllImport("user32.dll")]

public static extern bool DestroyIcon(IntPtr hIcon);

}

本人项目中使用的是WPF中自定义的鼠标,测试过,没有内存泄漏问题,放心使用。

原文地址:https://www.cnblogs.com/ysq0908/p/10268908.html