Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Changing the Systems Cursor in VB.net.

0.00/5 (No votes)
15 Jul 2008 2  
Replace a cursor system-wide and restore it to the original cursor.

Introduction

I have always come to this site for help so it's time for me to give back. This is my first post here so be gentle :P

The point of this article is to show you how to replace a cursor system-wide and specifically how to restore it to the original cursor once you're ready to do so.

Background

Changing a system cursor was cake for me, but a problem came about when I wanted to restore that system cursor back to the original cursor. Many suggested to use the LoadCursor or LoadImage API to restore the cursor, but it seemed (for me at least) that neither API worked in VB.net. So, on my own, I came up with the following solution.

Using the code

I'm not sure if it is the best way to do it but it seems to work fairly well. The main code from the sample project is as follows:

'Variable to save current cursor
Dim SavedCursor As Icon

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    'Save cursor
    SavedCursor = Icon.FromHandle(Cursors.Arrow.CopyHandle)

    'Change arrow cursor to mine
    Dim NewCursor As IntPtr = LoadCursorFromFile(Application.StartupPath & "\MyCross.cur")

    'Check
    If NewCursor = IntPtr.Zero Then
        'Error loading cursor from file
        Debug.WriteLine("Error loading cursor from file.")
        Return
    End If

    'Set the system cursor
    If SetSystemCursor(NewCursor, IDC_ARROW) = 0 Then
        'Error setting system cursor
        Debug.WriteLine("Error setting system cursor.")
        Return
    End If

    'Disable/enable buttons
    Button1.Enabled = False
    Button2.Enabled = True
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    'Get old cursor
    Dim OldCursor As IntPtr = SavedCursor.Handle

    'Set the system cursor
    SetSystemCursor(OldCursor, IDC_ARROW)

    'Disable/enable buttons
    Button1.Enabled = True
    Button2.Enabled = False
End Sub   

Points of Interest

This sample was written and tested in Visual Studio 2008 using the 3.5 .net framework. Any feedback would be great (especially if anyone has any improvements).

History

-Release 1 (July 15th, 2008)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here