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来触发按钮

相关推荐
FAREWELL0007518 分钟前
Unity学习总结篇(1)关于各种坐标系
学习·unity·c#·游戏引擎
编程乐趣33 分钟前
一个可拖拉实现列表排序的WPF开源控件
开源·c#·.net·wpf
Risehuxyc3 小时前
备份C#的两个类
c#
csdn_aspnet3 小时前
C# WinForm treeView 全选反选 点击过快节点选中状态未选中或选中状态未取消
c#·winform
爱编程的鱼3 小时前
C#接口(Interface)全方位讲解:定义、特性、应用与实践
java·前端·c#
Dongwoo Jeong5 小时前
UI架构的历史与基础入门
c#·mvc·mvvm·mvp·mvi·architecture
mascon5 小时前
C#自定义扩展方法 及 EventHandler<TEventArgs> 委托
开发语言·c#
冰茶_9 小时前
掌握LINQ:查询语法与方法语法全解析
sql·学习·microsoft·微软·c#·linq
与火星的孩子对话9 小时前
Unity3D开发AI桌面精灵/宠物系列 【六】 人物模型 语音口型同步 LipSync 、梅尔频谱MFCC技术、支持中英文自定义编辑- 基于 C# 语言开发
人工智能·unity·c#·游戏引擎·宠物·lipsync
她说彩礼65万9 小时前
C# 中的锁
开发语言·c#