0

I have found many pages describing how to prevent the blinking caret. Looks simple enough.

[DllImport("user32")]
public static extern bool HideCaret(IntPtr hWnd);

private void OnFocusEnterSpecificTextbox(object sender, EventArgs e)
{ HideCaret(SpecificTextbox.Handle); }

It's not working. When I click on the Textbox, there's the caret. I can breakpoint and see that I am hitting that code.

What boneheaded mistake am I making?

Mighty
  • 325
  • 2
  • 9
  • What are you trying to achieve by hiding the caret? Did you check the return value from `HideCaret` (and `GetLastError`)? – Luaan Sep 17 '19 at 10:05
  • I appreciate the quick reply. When I click my Run button, the focus jumps to one of the read-only textboxes on my form, and even highlights the text. I find that jarring, and I expect my users would, too. I'm getting a false return from HideCaret. Trying to figure out how to GetLastError, but my first stab caused an exception. It's late. I'll return to this tomorrow. – Mighty Sep 17 '19 at 10:21
  • 1
    Try something like this. `textBox1.GotFocus += (s1, e1) => { HideCaret(textBox1.Handle); };` – Rahul Nikate Sep 17 '19 at 10:29
  • 1
    Which event are you actually using? The method name is a bit ambiguous. You need to use `GotFocus`, not `Enter`. – Luaan Sep 17 '19 at 10:44

2 Answers2

1

This works (VS 2008 on Windows 7):

public partial class Form1 : Form
{
    [DllImport("user32")]
    public static extern bool HideCaret(IntPtr hWnd);


    public Form1()
    {
        InitializeComponent();
    }


    private void Form1_Load(object sender, EventArgs e)
    {
        textBox1.GotFocus += new EventHandler(textBox1_GotFocus);
    }


    void textBox1_GotFocus(object sender, EventArgs e)
    {
        HideCaret(textBox1.Handle);
    }
}
equin0x80
  • 303
  • 1
  • 9
  • 1
    Thanks. I got sucked in through Visual Studio surfacing Enter, but not GotFocus. I need to research that for the subtle differences. – Mighty Sep 18 '19 at 04:21
-1

Here's another way to stop blinking cursor in TextBox:

public partial class Form1 : Form
{
    [DllImport("user32.dll")]
    static extern bool HideCaret(IntPtr hWnd);
    public Form1()
    {
        InitializeComponent();
        textBox1.GotFocus += (s1, e1) => { HideCaret(textBox1.Handle); };
    }
}
Rahul Nikate
  • 6,192
  • 5
  • 42
  • 54