Working with the Cursor Object in Visual Basic

Introduction

Welcome to my article. Today, I would like to talk about the Cursor object and how you can utilize it properly from your Visual Basic program.

Cursors

According to MSDN, a cursor is a small picture whose location on the screen is controlled by a pointing device, such as a mouse, pen, or trackball. In the remainder of this overview, the term mouse refers to any pointing device.

When the user moves the mouse, the system moves the cursor accordingly. The cursor functions enable applications to create, load, display, animate, move, confine, and destroy cursors.

The Windows API

Before going into depth about the cursor object, I need to speak about some of the background technology used. This technology is known as the Windows API.

Now, What Is the Windows API?

The term API means Application Programming Interface. Any good program exposes some sort of API that can be used in other applications. Windows is no different. You have to remember that, in running Windows, you are indirectly executing code exposed by the Windows Operating System.

A simple action, such as opening a file, executes the desired functionality needed for the file to be run. Copying and pasting is also an example.

Then, you get the functions that run in the background, which you usually do not have to care about: keeping track of memory usage, obtaining a list of running programs. I can go on.

Where Are These APIs Stored?

The Windows system, or any system for that matter, is made up of a bunch of files, called DLLs amongst others. The term DLL means Dynamic Link Library. These files are dynamically linked with the Operating System to run the program associated with it.

The methods of the programs are locked away in these files, and these methods make your applications work.

Now, to get back on topic. We need to make use of the specific methods inside the specific Windows DLL files to do some nice stuff with the Windows Cursor.

Cursors

Add the namespaces necessary for the Windows API as well as to be able to read files:

Imports System.Runtime.InteropServices
Imports System.IO

Add the LoadCursorFromFile API Function:

   Private Declare Unicode Function LoadCursorFromFile Lib _
      "user32.dll" Alias "LoadCursorFromFileW" _
      (ByVal filename As String) As IntPtr

   Private FileName As String

Add the next Function:

   Private Shared Function CreateCursor(ByVal _
         filename As String) As Cursor
      Dim hCursor As IntPtr
      Dim result As Cursor = Nothing

      Try
         hCursor = LoadCursorFromFile(filename)
         If Not IntPtr.Zero.Equals(hCursor) Then
            result = New Cursor(hCursor)
         Else
            'could not create cursor
            Throw New ApplicationException("Could not _
               create cursor from file " & filename)
         End If

      Catch ex As Exception
         'log exception
      End Try

      Return result
   End Function

Add the following code behind a button’s click event:

   Private Sub Button2_Click(sender As Object, _
         e As EventArgs) Handles Button2.Click
      FileName = Path.Combine(Application.StartupPath, _
         "dinosaur.ani")

      Me.Cursor = CreateCursor(FileName)
   End Sub

The CreateCursor function creates a cursor with the help of the LoadCursorFromFile API function. A filename is sent as a parameter, and, if the filename is not valid, an error will be thrown. Inside the click event for the button, I specify where the cursor is and call the CreateCursor function to set the new cursor.

Hiding and Showing the Cursor Object

Hiding and showing the cursor is quite easy. All you need is the ShowCursor Function that is created in the following example:

   <DllImport("user32")> _
      Private Shared Function ShowCursor(ByVal bShow _
         As Int32) As Int32
   End Function

   ShowCursor(False)

Hides the Cursor

   ShowCursor(True)

Shows the cursor

Constraining a Cursor’s Position

In the next example, I will show you how you can constrain a cursor to only the form’s borders. This means that it will be impossible to move the mouse pointer outside the form’s bounds. Add the following code:

   <DllImport("user32")> _
      Private Shared Function ClipCursor(ByVal _
         lpRect As RECT) As Int32
   End Function

   <StructLayout(LayoutKind.Sequential)> _
   Private Structure RECT
      Public Left As Int32
      Public Top As Int32
      Public Right As Int32
      Public Bottom As Int32
   End Structure
   Private MouseTrap As RECT

   Public Sub RestoreCursor(ByRef ThisForm As _
         System.Windows.Forms.Form)
      With MouseTrap
         .Top = 0
         .Left = 0
         .Right = Screen.PrimaryScreen.Bounds.Width
         .Bottom = Screen.PrimaryScreen.Bounds.Height
      End With

      ClipCursor(MouseTrap)
   End Sub

   Private Sub MoveCursor()
      ' set the Current cursor, move the cursor's Position,
      ' and set its clipping rectangle to the form.
      Me.Cursor = New Cursor(Cursor.Current.Handle)
      Cursor.Position = New Point(Me.Left, Me.Top)
      Cursor.Clip = New Rectangle(Me.Left, Me.Top, _
         Me.Width, Me.Height) ', Me.Size)
   End Sub

With a combination of these functions, you will be able to constrain your mouse pointer, and then restore it.

Conclusion

Today, I have shown a few interesting tricks on what you can do with the simple Mouse Cursor. Until next time, bye!

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read