How to make a textbox non-selectable using C#

前端 未结 11 1862
轮回少年
轮回少年 2021-02-19 11:09

I\'m using C#/.NET for a Windows Forms application. I have a text box. How can I make the text box unselectable?

I don\'t want to disable the complete textbox.

11条回答
  •  感动是毒
    2021-02-19 11:54

    Old question, and I'm not completely happy with my hack of an answer to this problem, but if the original intention was to use the text box to display data without allowing it to be selected in any way, this is a method that has (so far) worked for me.

    First, the non-default properties of my text box:

    Multiline        = true
    ReadOnly         = true
    ScrollBars       = Both
    ShortcutsEnabled = false
    TabStop          = false
    WordWrap         = false
    

    Then mouse event handling. Both MouseMove and DoubleClick were mapped to trigger textBox1_MouseGeneral(), and I had additional actions happening in the Click event, thus the apparent duplication of the two event handlers.

        private void MouseEvent()
        {
            textBox1.SelectionLength = 0;
    
            focusControl.Focus(); // Move focus to another control
        }
    
        private void textBox1_Click(object sender, EventArgs e)
        {
            MouseEvent();
        }
    
        private void textBox1_MouseGeneral(object sender, EventArgs e)
        {
            MouseEvent();
        }
    

    You get a flash of a caret cursor, then textBox1 loses focus.

提交回复
热议问题