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

资源文件的使用与自定义光标的实现

本文从两个方面讲述.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;

    以上方式就是设定自定义光标的实现。当然不管是静态光标还是动态光标都需要自己设计之后方可引用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值