Jack
Jack

Reputation: 5768

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.

Upvotes: 3

Views: 9982

Answers (4)

Ira
Ira

Reputation: 764

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

Upvotes: 0

Craig Gidney
Craig Gidney

Reputation: 18316

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

Upvotes: 10

Hari Prakash
Hari Prakash

Reputation: 185

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;

Upvotes: 4

SLaks
SLaks

Reputation: 888293

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

Upvotes: 5

Related Questions