通过使用Windows API来获取当前鼠标的图案,不论是系统图片还是自定义图标都能够获取到,在这个示例中,为了方便测试,给Form1添加了一个KeyPress事件,在程序激活状态下,将鼠标移动到任意能使鼠标图案不同的地方,随便按下一个按键,将会将当前鼠标图案描绘到Form1窗体中。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace GetWindowsCurrentCursorByWindowsAPI
{
public partial class Form1 : Form
{
[StructLayout(LayoutKind.Sequential)]
struct CURSORINFO
{
public int cbSize;
public int flags;
public IntPtr hCursor;
public Point ptScreenPos;
}
[DllImport("user32.dll")]
static extern bool GetCursorInfo(out CURSORINFO pci);
private const int CURSOR_SHOWING = 0x00000001;
public Form1()
{
InitializeComponent();
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
CURSORINFO vCurosrInfo;
vCurosrInfo.cbSize = Marshal.SizeOf(typeof(CURSORINFO));
GetCursorInfo(out vCurosrInfo);
if ((vCurosrInfo.flags & CURSOR_SHOWING) != CURSOR_SHOWING) return;
Cursor vCursor = new Cursor(vCurosrInfo.hCursor);
Graphics vGraphics = Graphics.FromHwnd(Handle);
Rectangle vRectangle = new Rectangle(95, 50, 32, 32);
vGraphics.FillRectangle(new SolidBrush(BackColor), vRectangle);
vCursor.Draw(vGraphics, vRectangle);
}
}
}