c#鼠标绘制

有用的没用的,用的上的用不上的,能写的不能写的,反正想起来就写了,比如这篇,好像一般也没什么用,emmm,或许,做录制软件的时候可以用一下。

顾名思义,本篇主要就是来实现将鼠标的指针样式给绘制成图片,显示或者保存下来。以下会通过两种方式实现,一种是C#自带的Cursor,另一种就是用Windows Api;下面分别写下两种方式的实现代码以及优势和缺陷

第一种使用C#自带的Cursor,这种方式使用起来比较简单,但是没办法正确获取到程序页面以外的指针形状

private void button1_Click(object sender, EventArgs e)

{

Graphics graphics = pictureBox1.CreateGraphics();

graphics.Clear(pictureBox1.BackColor);

int x=Cursor.Position.X;

int y=Cursor.Position.Y;

Cursor.Draw(graphics, new Rectangle(1,1,50,50));

//以拉伸格式绘制

// Cursor.DrawStretched(pictureBox1.CreateGraphics(), new Rectangle(1, 1, 50, 50));

label1.Text = $"坐标:{x},{y}";

}

第二种使用Windows Api,这种方式就比较全面,可以弥补上面那种方式的缺点。

/// <summary>

/// 获取鼠标信息

/// </summary>

/// <param name="cInfo"></param>

/// <returns></returns>

DllImport("user32.dll", EntryPoint = "GetCursorInfo")

private static extern bool GetCursorInfo(ref CURSORINFO cInfo);

/// <summary>

/// 将指定的图标从另一个模块复制到当前模块。

/// </summary>

/// <param name="hIcon"></param>

/// <returns></returns>

DllImport("user32.dll", EntryPoint = "CopyIcon")

private static extern IntPtr CopyIcon(IntPtr hIcon);

/// <summary>

/// 获取有关指定图标或光标的信息

/// </summary>

/// <param name="hIcon"></param>

/// <param name="iInfo"></param>

/// <returns></returns>

DllImport("user32.dll", EntryPoint = "GetIconInfo")

private static extern bool GetIconInfo(IntPtr hIcon, out ICONINFO iInfo);

private (int x, int y, Bitmap bmp) CaptureCursor()

{

CURSORINFO cURSORINFO = new CURSORINFO();

cURSORINFO.cbSize = Marshal.SizeOf(cURSORINFO);

if (GetCursorInfo(ref cURSORINFO))

{

if (cURSORINFO.flags == 0x00000001)

{

IntPtr icon = CopyIcon(cURSORINFO.hCursor);

ICONINFO iCONINFO;

if (GetIconInfo(icon, out iCONINFO))

{

int x = cURSORINFO.ptScreenPos.X - iCONINFO.xHotspot;

int y = cURSORINFO.ptScreenPos.Y - iCONINFO.yHotspot;

Bitmap bmp = Icon.FromHandle(icon).ToBitmap();

return (x, y, bmp);

}

}

}

return (0,0,null);

}

private void button3_Click(object sender, EventArgs e) { var cursor = CaptureCursor(); pictureBox1.Image = cursor.bmp; label1.Text = $"坐标:{cursor.x},{cursor.y}"; }

3.下面看下实现效果,当鼠标在界面外时,我们主要通过Tab和Enter来触发按钮

相关推荐
xiaoshuaishuai89 小时前
C# AvaloniaUI 中旋转
开发语言·c#
weixin_428005309 小时前
C#调用 AI学习从0开始-第2阶段(Function Calling+工具调用智能体)-第9天实战-实现计算器工具
开发语言·学习·c#·functioncalling·ai实现计算器工具
guygg8810 小时前
基于C# + Halcon的通用ROI绘制工具
stm32·单片机·c#
双河子思10 小时前
《代码整洁之道》——读书笔记(持续更新)
开发语言·c++·c#
诙_10 小时前
unity——C#
unity·c#·游戏引擎
cici1587411 小时前
C# LAS 点云读取与处理工具
stm32·单片机·c#
OnlyEasyCode11 小时前
C# 发送QQ邮箱验证码or其他
开发语言·c#
123的故事13 小时前
工具分享(2)-NSmartProxy内网穿透工具。
c#·.net·nsmartproxy
SunnyDays101114 小时前
使用 C# 添加、修改和删除 Excel VBA 宏 (无需 Microsoft Office Interop)
c#·excel··vba