How to hide the TextBox caret in .NETCF

I was trying to help a developer today in the smart device forums who wanted to hide the caret in the TextBox control. I started playing around with the Windows Mobile Platform SDK and I stumbled upon the methods HideCaret() and ShowCaret().

The outcome is this simple inherited TextBox control I decided to call TextBoxWithoutCaret šŸ™‚

class TextBoxWithoutCaret : TextBox
{
    [DllImport("coredll.dll")]
    static extern bool HideCaret(IntPtr hwnd);
 
    [DllImport("coredll.dll")]
    static extern bool ShowCaret(IntPtr hwnd);
 
    protected override void OnGotFocus(EventArgs e)
    {
        base.OnGotFocus(e);
        HideCaret(Handle);
    }
 
    protected override void OnLostFocus(EventArgs e)
    {
        base.OnLostFocus(e);
        ShowCaret(Handle);
    }
}

Every time the TextBox control is focused I hide the caret and enable it again when focus is lost. This doesn’t really make much practical sense and the only reason I do this is because HideCaret() is described to perform a cumulative operation meaning ShowCaret() must be called the same number of times HideCaret() was called for the caret to be visible again.

Leave a Reply

Your email address will not be published. Required fields are marked *