C#繪制鼠標指針的示例代碼
前言
有用的沒用的,用的上的用不上的,能寫的不能寫的,反正想起來就寫了,比如這篇,好像一般也沒什么用,emmm,或許,做錄制軟件的時候可以用一下。
顧名思義,本篇主要就是來實現(xiàn)將鼠標的指針樣式給繪制成圖片,顯示或者保存下來。以下會通過兩種方式實現(xiàn),一種是C#自帶的Cursor,另一種就是用Windows Api;下面分別寫下兩種方式的實現(xiàn)代碼以及優(yōu)勢和缺陷
開發(fā)環(huán)境:.NET Framework版本:4.8
開發(fā)工具:Visual Studio 2022
實現(xiàn)步驟
第一種使用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>
/// 將指定的圖標從另一個模塊復(fù)制到當(dāng)前模塊。
/// </summary>
/// <param name="hIcon"></param>
/// <returns></returns>
[DllImport("user32.dll", EntryPoint = "CopyIcon")]
private static extern IntPtr CopyIcon(IntPtr hIcon);
/// <summary>
/// 獲取有關(guān)指定圖標或光標的信息
/// </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}";
}下面看下實現(xiàn)效果,當(dāng)鼠標在界面外時,我們主要通過Tab和Enter來觸發(fā)按鈕
實現(xiàn)效果

到此這篇關(guān)于C#繪制鼠標指針的示例代碼的文章就介紹到這了,更多相關(guān)C#鼠標指針內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實現(xiàn)XML與實體類之間相互轉(zhuǎn)換的方法(序列化與反序列化)
這篇文章主要介紹了C#實現(xiàn)XML與實體類之間相互轉(zhuǎn)換的方法,涉及C#序列化與反序列化操作的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2016-06-06
C#?Winform實現(xiàn)復(fù)制文件顯示進度
這篇文章主要介紹了C#?Winform實現(xiàn)復(fù)制文件顯示進度,用進度條來顯示復(fù)制情況,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-07-07
C#創(chuàng)建windows系統(tǒng)用戶的方法
LINQ基礎(chǔ)之Intersect、Except和Distinct子句

