在C#中,获取当前光标图标(即鼠标指针图标)通常涉及使用Windows API函数。由于.NET Core和.NET 5+不再直接封装所有Windows API细节,因此需要使用P/Invoke
(平台调用)来调用这些函数。
以下是一个示例,展示如何获取当前光标图标的句柄(IntPtr
),然后可以进一步处理该图标(例如保存为文件或进行其他操作):
using System;
using System.Runtime.InteropServices;
using System.Drawing;
public class CursorHelper
{
// 获取当前光标的句柄
[DllImport("user32.dll")]
private static extern IntPtr GetCurrentCursor();
// 获取光标的位图信息
[DllImport("user32.dll")]
private static extern IntPtr GetIconInfo(IntPtr hIcon, out ICONINFO pIconInfo);
[StructLayout(LayoutKind.Sequential)]
public struct ICONINFO
{
public bool fIcon;
public IntPtr hbmColor;
public IntPtr hbmMask;
public int xHotspot;
public int yHotspot;
}
// 释放图标句柄
[DllImport("user32.dll")]
private static extern bool DestroyIcon(IntPtr hIcon);
}
public class Program
{
static void Main(string[] args)
{
IntPtr hCursor = CursorHelper.GetCurrentCursor();
if (hCursor != IntPtr.Zero)
{
CursorHelper.ICONINFO iconInfo;
if (CursorHelper.GetIconInfo(hCursor, out iconInfo))
{
// 处理位图(颜色和掩码)
// 注意:这里只是获取了位图的句柄,您可能需要进一步处理,例如保存为文件
Console.WriteLine("成功获取光标图标信息。");
// 释放资源
if (iconInfo.hbmColor != IntPtr.Zero)
DeleteObject(iconInfo.hbmColor);
if (iconInfo.hbmMask != IntPtr.Zero)
DeleteObject(iconInfo.hbmMask);
DestroyIcon(hCursor);
}
}
else
{
Console.WriteLine("未检测到光标或无法获取光标句柄。");
}
}
[DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr hObject);
}
.cur
或.ico
),需要进一步处理位图数据,例如使用Bitmap
类保存为图像文件。如果您希望将当前光标保存为图像文件(例如PNG),可以使用以下扩展方法:
using System.Drawing.Imaging;
public static class CursorExtensions
{
public static void SaveAsPng(IntPtr hCursor, string filePath)
{
ICONINFO iconInfo;
if (CursorHelper.GetIconInfo(hCursor, out iconInfo))
{
using (Bitmap bmp = Bitmap.FromHbitmap(iconInfo.hbmColor))
{
bmp.Save(filePath, ImageFormat.Png);
}
if (iconInfo.hbmColor != IntPtr.Zero)
DeleteObject(iconInfo.hbmColor);
if (iconInfo.hbmMask != IntPtr.Zero)
DeleteObject(iconInfo.hbmMask);
CursorHelper.DestroyIcon(hCursor);
}
}
}
然后在Main
方法中调用:
CursorExtensions.SaveAsPng(hCursor, "current_cursor.png");
此方法将当前光标保存为current_cursor.png
文件。请确保应用程序具有写入文件的权限,并且路径有效。
通过上述方法,您可以在C#中获取当前光标的图标,并根据需要进行进一步处理或保存。
领取专属 10元无门槛券
手把手带您无忧上云