Custom cursor in C# Winforms

2019-06-03 02:25发布

问题:

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.

回答1:

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


回答2:

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



回答3:

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;


回答4:

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);