博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

怎样在wpf中自定义鼠标指针

Posted on 2012-02-10 15:49  十一郞  阅读(357)  评论(0编辑  收藏  举报

看看WPF Cursor类的两个构造函数吧:

public Cursor(Stream cursorStream) public Cursor(string cursorFile)

 

恩, 均要求用 ani 或 cur, 无语啊,我要使用一张普通图片呢? 或者甚至是在程序内存中动态生成一张图片而生成鼠标指针呢?
于是乎, 我们可以折腾出如下代码, 它可以从由一张图片来创建鼠标指针:

    ///<summary>     /// This class allow you create a Cursor form a Bitmap     ///</summary>    internalclass BitmapCursor : SafeHandle     {
       
publicoverridebool IsInvalid         {             get             {                 return handle == (IntPtr)(-1);             }         }
       
publicstatic Cursor CreateBmpCursor(Bitmap cursorBitmap)         {
            var c
=new BitmapCursor(cursorBitmap);
           
return CursorInteropHelper.Create(c);         }
       
protected BitmapCursor(Bitmap cursorBitmap)             : base((IntPtr)(-1), true)         {             handle = cursorBitmap.GetHicon();         }
       
protectedoverridebool ReleaseHandle()         {             bool result = DestroyIcon(handle);
            handle
= (IntPtr)(-1);
           
return result;         }
        [DllImport(
"user32")]         privatestaticexternbool DestroyIcon(IntPtr hIcon);     }

 

下面是一段示例代码:

        privatestatic Cursor CreateMyCursor()         {             constint w =25;             constint h =25;             constint 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);         }

 

 

有人会说"啊!Bitmap? WinForm的! 就不可以从WPF的图像来生成么?" 那么免费赠送如下函数:

        publicstatic Bitmap BitmapSourceToBitmap(this 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;             }         }

 

 

 

 

转载自:http://www.cnblogs.com/zhouyinhui/archive/2010/05/28/1746502.html