Tag Archives: caret

Hide/Show the Cursor’s Caret using VB and VB.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (5 votes, average: 5.00 out of 5)
 

There may be times when you don’t want your textbox or combobox to show the cursor’s caret position (blinking cursor). Thanks to a couple API calls, its easy to both hide and show the caret from the user. Microsoft made available the HideCaret and ShowCaret api functions.

I want to explain alittle more how the functions operate. Whenever you want to hide the caret using the HideCaret api call, say on one of your textbox controls, the target textbox needs to have ownership of the caret at the time the Hide Caret function is executed. Whenever the textbox loses ownership of the caret it will be reset back to the default setting. For example you call the HideCaret function which successfully hides the blinking cursor in the target textbox control. You then click on a button or another control that gets focus/ownership of the caret, then the caret/blinking cursor will be shown again in the target textbox when the user clicks or gives focus to the target textbox again. In other words, whenever ownership of the caret changes from one control to another then the Caret will reset back to its default setting. So, if you want the caret to always remain hidden from the user in your textbox, then you can do a simple trick to keep the blinking cursor from being shown even when it changes ownership.


First of all, you need to get the code for the two API calls…

VB.NET

Private Declare Function HideCaret Lib “user32? (ByVal wHandle As Int32) As Int32

Private Declare Function ShowCaret Lib “user32? (ByVal wHandle As Int32) As Int32

VB 6.0

Private Declare Function HideCaret Lib “user32? (ByVal wHandle As Long) As Long

Private Declare Function ShowCaret Lib “user32? (ByVal wHandle As Long) As Long

The functions are easy to use. All you have to do is call the two functions with the handle of the control whose caret you want to hide or show in the wHandle parameter like below…

VB.NET

    HideCaret(TextBox1.Handle.ToInt32)

    ShowCaret(TextBox1.Handle.ToInt32)

VB 6.0

    HideCaret Text1.hWnd

    ShowCaret Text1.hWnd

The codes above set to Hide/Show the caret in a textbox control.


If you want the cursor to never be shown in a textbox control, then simply put the HideCaret code in the Textbox_GotFocus() event. Like below…

VB.NET

Private Sub TextBox1_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus

HideCaret(TextBox1.Handle.ToInt32)

End Sub

VB 6.0

Private Sub Text1_GotFocus()

    HideCaret(Text1.hWnd) 

End Sub

With the code above, now each time the textbox control gets focus and ownership of the caret it will automatically call the HideCaret function. Thus the user should never see the blinking cursor at all.


That’s all for this tip I guess. 🙂

Jason

Minor Revision: 2015