原文:
[WPF]自定义鼠标指针
于是乎, 我们可以折腾出如下代码, 它可以从由一张图片来创建鼠标指针:
[WPF]自定义鼠标指针
周银辉
看看WPF Cursor类的两个构造函数吧:
public
Cursor(Stream cursorStream)
public Cursor( string cursorFile)
public Cursor( string cursorFile)
恩, 均要求用 ani 或 cur, 无语啊,我要使用一张普通图片呢? 或者甚至是在程序内存中动态生成一张图片而生成鼠标指针呢?
于是乎, 我们可以折腾出如下代码, 它可以从由一张图片来创建鼠标指针:
///
<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);
}
protected BitmapCursor(Bitmap cursorBitmap)
: base ((IntPtr)( - 1 ), true )
{
handle = cursorBitmap.GetHicon();
}
protected override bool ReleaseHandle()
{
bool result = DestroyIcon(handle);
handle = (IntPtr)( - 1 );
return result;
}
[DllImport( " user32 " )]
private static extern bool DestroyIcon(IntPtr hIcon);
}
/// 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);
}
protected BitmapCursor(Bitmap cursorBitmap)
: base ((IntPtr)( - 1 ), true )
{
handle = cursorBitmap.GetHicon();
}
protected override bool ReleaseHandle()
{
bool result = DestroyIcon(handle);
handle = (IntPtr)( - 1 );
return result;
}
[DllImport( " user32 " )]
private static extern bool DestroyIcon(IntPtr hIcon);
}
下面是一段示例代码:
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);
}
{
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);
}
有人会说"啊!Bitmap? WinForm的! 就不可以从WPF的图像来生成么?"
那么免费赠送如下函数:
public
static
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;
}
}
{
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;
}
}