How to make a textbox non-selectable using C#

前端 未结 11 1915
轮回少年
轮回少年 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:58

    @Mystere Man: You might want a text box that cannot be used all the time. For example, I allow the user to create text boxes on a canvas and drag them around. To prevent them from selecting and moving text when they are dragging I need to disallow user input, and text selection also needs to be disabled because it causes a delay which messes up my drag function. In my application the user can only edit a text box when he has double clicked on it, and must then click outside of the text box to be able to move it again.

    I basically have this code (where t is a TextBox):

    // Prevent text entry
    t.IsReadOnly = true;
    
    // Prevent text selection
    t.Focusable = false;
    

    This behaviour is preferable to disabling the whole control (t.Enabled = false), since that would also stop mousedown and doubleclick events, which would stop dragging and changing from edit to drag mode from working. Not to mention that the text box would go grey.

    0 讨论(0)
  • 2021-02-19 12:04

    You have a couple of options:

    1. Use a Label control instead.
    2. Set textBox.Enabled = false to prevent selection (see here).
    0 讨论(0)
  • 2021-02-19 12:05

    Probably the best way is to put a label behind it, and when you want to make the textbox disabled, hide it and show the label in its place.

    0 讨论(0)
  • 2021-02-19 12:06

    In the 'Enter' event of the textbox set the ActiveControl to something else:

        private void txtMyTextbox_Enter(object sender, EventArgs e)
        {
            ActiveControl = objMyOtherControl;
        }
    
    0 讨论(0)
  • 2021-02-19 12:08
    private void textBox1_Click(object sender, EventArgs e)
            {
                this.textBox1.SelectionStart = this.textBox1.Text.Length;
            }
    

    And don't forget that: read only=true

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