您的位置:首页 > 编程语言 > C#

C# WinForm编程中的一点小收获(二)

2005-08-24 13:13 330 查看
资源文件的使用与自定义光标的实现
本文从两个方面讲述.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;
以上方式就是设定自定义光标的实现。当然不管是静态光标还是动态光标都需要自己设计之后方可引用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: