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

  • 相关阅读:
    显著提升程序员身心健康和工作效率的装备有哪些?
    谁控制了我们的浏览器?
    利用Http Authentication Url+csrf劫持路由器DNS
    如​何​删​除​G​P​T​保​护​分​区
    Linux定时器的使用
    缺少 mcrypt 扩展。请检查 PHP 配置。(phpmyadmin)
    xxx is not in the sudoers file
    linux mysql 找不到 <mysql/mysql.h>
    C++面试常见问题(持续更新)
    代码模板(new)
  • 原文地址:https://www.cnblogs.com/ysq0908/p/10268908.html
Copyright © 2011-2022 走看看