Search code examples
c#textboxcursorlabel

How to prevent blinking cursor for TextBox in C# (little bit more complicated)


I've had a problem with editing Label in GUI so I decided to transform that label to textbox with BackColor as the background has to make it look exactly as label do, but after focusing on that textbox will blinking cursor appear. It's pretty unsightly & the only way I've found is to set the property Enabled to false, but I also require from that textbox to do something after doubleclick & only one click. So if it isn't enabled control, it doesn't react to double-clicking.

Essentially I want to behave that textbox as label by default until it's clicked once, if it is double-clicked, then will be performed some function only rewriting the text property of other textbox. So if it is clicked once, I'd like to make the textbox look like real textbox for text insert with cursor blinking. After pushing Enter it would again transform to the 'fake' label without cursor blinking after focus.

Is that possible?

P.S. I'm sorry about the duplicate, but I couldn't understand how to implement f.e. [DllImport("user32")] it underlines 'DllImport' with red line and the comment is:

The type or namespace 'DllImport' could not be found.

detailed:

Error   1   The type or namespace name 'DllImport' could not be found (are you missing a using directive or an assembly reference?) C:\Users\**\Visual Studio 2013\Projects\Práce\Rozvržení práce\Rozvržení práce\Form1.cs  17  10  Rozvržení práce

Error   2   The type or namespace name 'DllImportAttribute' could not be found (are you missing a using directive or an assembly reference?)    C:\Users\**\Visual Studio 2013\Projects\Práce\Rozvržení práce\Rozvržení práce\Form1.cs  17  10  Rozvržení práce

Practically solved by a comment

( Implement [System.Runtime.InteropServices.DllImport("user32")] instead =D – Sinatr )

Let me just ask:

How can I set blinking cursor again? I suppose by editing static extern bool HideCaret(IntPtr hWnd);, but how?


Solution

  • It is called the "caret". It only shows up when the TextBox gets the focus. But since you don't want the user to change anything, it also doesn't make sense to allow it to get the focus. So the simple workaround is to defeat focusing attempts. Add a class to your project and paste the code shown below. Compile and drop it from the top of the toolbox onto your form.

    using System;
    using System.Windows.Forms;
    
    class TextBoxLabel : TextBox {
        public TextBoxLabel() {
            this.SetStyle(ControlStyles.Selectable, false);
            this.TabStop = false;
        }
        protected override void WndProc(ref Message m) {
            // Workaround required since TextBox calls Focus() on a mouse click
            // Intercept WM_NCHITTEST to make it transparent to mouse clicks
            if (m.Msg == 0x84) m.Result = IntPtr.Zero;
            else base.WndProc(ref m);
        }
    }