Custom cursor in C# Winforms

房东的猫 提交于 2019-12-04 15:40:55

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!