开发者

Custom cursor in C# Winforms

Does anyone know of an easy 开发者_高级运维way to use a custom cursor? I have both a .cur and .png of my cursor. I tried adding it as a resource to my project and also tried including it as a file in the project. Ideally I'd like to embed it but I just want to get it working.

When I use Cursor cur = new Cursor("mycursor.cur") I get "Image format is not valid. The image file may be corrupted". I tried this http://mahesg.wordpress.com/2008/02/09/embedding-cursor/ but it didn't work. Using WinForm1.Properties.Resources.mycursor returns a byte[] which I have no idea how to convert into a Cursor type.


For some reason the cursor class is far too picky about what it will read. You can create the handle yourself using the windows API then pass that to the cursor class.

C#:

//(in a class)
public static Cursor ActuallyLoadCursor(String path) {
    return new Cursor(LoadCursorFromFile(path))
}
[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern IntPtr LoadCursorFromFile(string fileName);

VB.Net:

'(in a class)'
Public Shared Function ActuallyLoadCursor(path As String) As Cursor
    Return New Cursor(LoadCursorFromFile(path))
End Function
<System.Runtime.InteropServices.DllImport("user32.dll")>
Private Shared Function LoadCursorFromFile(fileName As String) As IntPtr
End Function


Write new Cursor(new MemoryStream(Properties.Resources.mycursor))


Adding custom icon to cursor in C# :

Add Icon file to Project resources (ex : Processing.ico)

And in properties window of image switch "Build Action" to "Embedded"

Cursor cur = new Cursor(Properties.Resources.**Imagename**.Handle);
this.Cursor = cur;

Ex:

Cursor cur = new Cursor(Properties.Resources.Processing.Handle);
this.Cursor = cur;


Objective: To change cursor to a custom cursor when user need to do cut activity in a sample winforms UI

Do this it will work

  1. Add the icon file (e.g cut.ico) to the project
  2. Now add icon to project resource To add to resource right click on project->properties->Resources Now drop the ico file from the project folder (U added to project folder in point 1) on Resources
  3. This code should do the trick
System.Windows.Forms.Cursor _customCutCursor = 
   new System.Windows.Forms.Cursor(Properties.Resources.cut.Handle);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜