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中自定義的鼠標,測試過,沒有內存泄漏問題,放心使用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM