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

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

解决办法以下:测试

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

public void SetCursor(System.Drawing.Bitmap cursor)orm

{对象

    try继承

    {事件

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

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

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

 

        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中自定义的鼠标,测试过,没有内存泄漏问题,放心使用。

相关文章
相关标签/搜索