資源文件的使用與自定義光標的實現
本文從兩個方面講述.net中自定義光標的實現,部分是參考“孟子”前輩的資料,以示說明。
首先要明白一個知識點:光標的分類
光標分為兩大類,一是靜態光標(*.cur),一是動態光標(*.ani)。這兩類光標又有彩色和單像素之分。一般常見的靜態光標多數是單像素的,.net中可以直接支持這種光標。而對于彩色或動態光標則是有256色甚至更高像素組成的動畫光標,在.net中若要支持動態光標或彩色光標需要調用win32 api實現。
1:在.net中利用資源文件實現自定義靜態光標(以下為msdn原文)
// the following generates a cursor from an embedded resource.
// to add a custom cursor, create or use an existing 16x16 bitmap
// 1. add a new cursor file to your project:
// file->add new item->local project items->cursor file
// 2. select 16x16 image type:
// image->current icon image types->16x16
// --- to make the custom cursor an embedded resource ---
// in visual studio:
// 1. select the cursor file in the solution explorer
// 2. choose view->properties.
// 3. in the properties window switch "build action" to "embedded"
// on the command line:
// add the following flag:
// /res:cursorfilename.cur,namespace.cursorfilename.cur
//
// where "namespace" is the namespace in which you want to use the cursor
// and "cursorfilename.cur" is the cursor filename.
// the following line uses the namespace from the passed-in type
// and looks for customcursor.mycursor.cur in the assemblies manifest.
// note: the cursor name is acase sensitive.
this.cursor = new cursor(gettype(), "mycursor.cur");
此處需要注意的是在調用的時候,mycursor.cur為資源文件的名稱,大小寫區分。如下圖所示:

則資源文件名稱應該為cursor.block.cur,以命名空間的形式來訪問資源。
2:.net中實現自定義彩色光標和動態光標
以下為引用win32 api函數,用于創建自定義光標、設置光標等操作。
[dllimport("user32.dll")]
public static extern intptr loadcursorfromfile( string filename );
[dllimport("user32.dll")]
public static extern intptr setcursor( intptr cursorhandle );
[dllimport("user32.dll")]
public static extern uint destroycursor( intptr cursorhandle );
調用自定義光標則可以如下操作:
cursor mycursor = new cursor(cursor.current.handle);
//dinosau2.ani為windows自帶的光標:
intptr colorcursorhandle = loadcursorfromfil(@"c:/winnt/cursors/dinosau2.ani" );
mycursor.gettype().invokemember("handle",bindingflags.public | bindingflags.nonpublic | bindingflags.instance | bindingflags.setfield,null,mycursor, new object [] { colorcursorhandle } );
this.cursor = mycursor;
以上方式就是設定自定義光標的實現。當然不管是靜態光標還是動態光標都需要自己設計之后方可引用。
新聞熱點
疑難解答