Click Star to Rate Post
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…
Private Declare Function HideCaret Lib “user32? (ByVal wHandle As Int32) As Int32
Private Declare Function ShowCaret Lib “user32? (ByVal wHandle As Int32) As Int32
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…
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…
Private Sub TextBox1_GotFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.GotFocus
Private Sub Text1_GotFocus()
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. 🙂
Minor Revision: 2015