C#繪制鼠標(biāo)指針的示例代碼
前言
有用的沒用的,用的上的用不上的,能寫的不能寫的,反正想起來就寫了,比如這篇,好像一般也沒什么用,emmm,或許,做錄制軟件的時候可以用一下。
顧名思義,本篇主要就是來實現(xiàn)將鼠標(biāo)的指針樣式給繪制成圖片,顯示或者保存下來。以下會通過兩種方式實現(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 = $"坐標(biāo):{x},{y}"; }
第二種使用Windows Api,這種方式就比較全面,可以彌補(bǔ)上面那種方式的缺點。
/// <summary> /// 獲取鼠標(biāo)信息 /// </summary> /// <param name="cInfo"></param> /// <returns></returns> [DllImport("user32.dll", EntryPoint = "GetCursorInfo")] private static extern bool GetCursorInfo(ref CURSORINFO cInfo); /// <summary> /// 將指定的圖標(biāo)從另一個模塊復(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)指定圖標(biāo)或光標(biāo)的信息 /// </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 = $"坐標(biāo):{cursor.x},{cursor.y}"; }
下面看下實現(xiàn)效果,當(dāng)鼠標(biāo)在界面外時,我們主要通過Tab和Enter來觸發(fā)按鈕
實現(xiàn)效果
到此這篇關(guān)于C#繪制鼠標(biāo)指針的示例代碼的文章就介紹到這了,更多相關(guān)C#鼠標(biāo)指針內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
BootStrap mvcpager分頁樣式(get請求,刷新頁面)
這篇文章主要介紹了BootStrap mvcpager分頁樣式(get請求,刷新頁面)的相關(guān)資料,通過引入相關(guān)文件,實現(xiàn)此功能,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-08-08