【WPF】自定義鼠標樣式


 /// <summary>
    /// This class allow you create a Cursor form a Bitmap
    /// </summary>
    internal class BitmapCursor : SafeHandle
    {
        public override bool IsInvalid
        {
            get
            {
                return handle == (IntPtr)(-1);
            }
        }

        public static Cursor CreateBmpCursor(Bitmap cursorBitmap)
        {
            var c = new BitmapCursor(cursorBitmap);
            return CursorInteropHelper.Create(c);
        }

        public static Bitmap BitmapSourceToBitmap(BitmapSource source)
        {
            using (var stream = new MemoryStream())
            {
                var e = new BmpBitmapEncoder();
                e.Frames.Add(BitmapFrame.Create(source));
                e.Save(stream);
                var bmp = new Bitmap(stream);
                return bmp;
            }
        }

        protected BitmapCursor(Bitmap cursorBitmap)
            : base((IntPtr)(-1), true)
        {
            handle = cursorBitmap.GetHicon();
        }

        protected override bool ReleaseHandle()
        {
            bool result = DestroyIcon(handle);

            handle = (IntPtr)(-1);

            return result;
        }

        private static Cursor CreateMyCursor()
        {
            const int w = 25;
            const int h = 25;
            const int f = 4;

            var bmp = new Bitmap(w, h);

            Graphics g = Graphics.FromImage(bmp);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            var pen = new Pen(Brushes.Black, 2.0F);

            g.DrawEllipse(pen, new Rectangle(f, f, w - 2 * f, w - 2 * f));

            g.Flush();
            g.Dispose();
            pen.Dispose();

            return BitmapCursor.CreateBmpCursor(bmp);
        }

        [DllImport("user32")]
        private static extern bool DestroyIcon(IntPtr hIcon);
    }

 

WPF 中每個光標通過一個System.Windows.Input.Cursor表示,獲取Cursor對象的最簡單方法是使用Cursor類(位於System.Windows.Input名稱空間)的靜態屬性。

如:

this.Cursor=Cursors.wait;  或<Button Cursor="wait">help</Button>

但是有一個例外,通過使用ForceCursor屬性,父元素會覆蓋子元素的光標位置,當把該屬性設置為true時,會忽略子元素的Cursor屬性,並且父元素的光標會被應用到內部的所有內容。

為了移除應用程序范圍的光標覆蓋設置,需要將Mouse.OverrideCursor屬性設置為null

 


免責聲明!

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



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