How do I hide the input caret in a System.Windows.Forms.TextBox?

前端 未结 5 1818
暖寄归人
暖寄归人 2021-01-12 07:21

I need to display a variable-length message and allow the text to be selectable. I have made the TextBox ReadOnly which does not allow the text to be edited, but the input c

相关标签:
5条回答
  • 2021-01-12 07:46

    When using the win32 call don't forget to hide the cursor in the textbox's GotFocus event.

    0 讨论(0)
  • 2021-01-12 07:52

    If you disable the text box (set Enable=false), the text in it is still scrollable and selectable. If you don't like the visual presentation of a disabled text box (gray background usually) you can manually override the colors.

    Be warned, manually overriding colors is going to make your form/control look weird on systems that do not use the default color/theme settings. Don't assume that because your control is white that everyone's control is going to be white. That's why you should always use the system colors whenever possible (defined in the System.Drawing.SystemColors enumeration) such as SystemColors.ControlLight.

    0 讨论(0)
  • 2021-01-12 07:58

    AFAIK, this cannot be done. The TextBox control is a funny control because it actually has a lot of behaviour that can't be modified due to the way it taps into the operating system. This is why many of the cool custom TextBoxes are written from scratch.

    I am afraid you may not be able to do what you wish to do :(

    0 讨论(0)
  • 2021-01-12 07:59

    You can do through a win32 call

    [DllImport("user32.dll")]
    static extern bool HideCaret(IntPtr hWnd);
    public void HideCaret()
    {
        HideCaret(someTextBox.Handle);
    }
    
    0 讨论(0)
  • 2021-01-12 08:11

    Just for completeness, I needed such a functionality for using with a DevExpress WinForms TextEdit control.

    They already do provide a ShowCaret and a HideCaret method, unfortunately they are protected. Therefore I created a derived class that provides the functionality. Here is the full code:

    public class MyTextEdit : TextEdit
    {
        private bool _wantHideCaret;
    
        public void DoHideCaret()
        {
            HideCaret();
    
            _wantHideCaret = true;
        }
    
        public void DoShowCaret()
        {
            ShowCaret();
    
            _wantHideCaret = false;
        }
    
        protected override void OnGotFocus(EventArgs e)
        {
            base.OnGotFocus(e);
    
            if (_wantHideCaret)
            {
                HideCaret();
            }
        }
    }
    

    To use the code, simply use the derived class instead of the original TextEdit class in your code and call DoHideCaret() anywhere, e.g. in the constructor of your form that contains the text edit control.

    Maybe this is helpful to someone in the future.

    0 讨论(0)
提交回复
热议问题