如何自定義Winform應(yīng)用程序的鼠標(biāo)圖片?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。
首先,建立圖片與鼠標(biāo)的對(duì)應(yīng)關(guān)系。
class MouseStyle { [DllImport("user32.dll")] public static extern IntPtr SetCursor(IntPtr cursorHandle); static MouseStyle() { InitMouseStyle(); } private static void InitMouseStyle() { if (Hand == null) { Hand = SetCursor("Image//Hand.png"); } if (Arrow == null) { Arrow = SetCursor("Image//Arrow.png"); } } ////// 鼠標(biāo)手型樣式 /// public static Cursor Hand = null; ////// 鼠標(biāo)指針樣式 /// public static Cursor Arrow = null; ////// 設(shè)置鼠標(biāo)樣式 /// /// 自定義的鼠標(biāo)樣式文件 ///鼠標(biāo)樣式 private static Cursor SetCursor(string fileName) { //文件的絕對(duì)路徑,在debug下 var path = System.IO.Path.GetFullPath(fileName) ; //畫(huà)圖 Bitmap bit = (Bitmap)Bitmap.FromFile(path, true); Bitmap myNewCursor = new Bitmap(bit.Width, bit.Height); Graphics g = Graphics.FromImage(myNewCursor); g.Clear(Color.FromArgb(0, 0, 0, 0)); //箭頭和手型有點(diǎn)不一樣 if (System.IO.Path.GetFileName(fileName).Equals("Hand.png")) { g.DrawImage(bit, bit.Width / 2 - 15, bit.Height / 2, bit.Width / 2, bit.Height / 2); } else { g.DrawImage(bit, bit.Width / 2 - 15, bit.Height / 2, bit.Width / 2, bit.Height / 2); } Cursor cursor; //獲取圖片的句柄 try { cursor = new Cursor(myNewCursor.GetHicon()); } catch { cursor = new Cursor(Icon.FromHandle(myNewCursor.GetHicon()).Handle); } //釋放資源 g.Dispose(); return cursor; } }