Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable the selection on a TextBox

I want to disable selecting text and clicking in the middle of text in a TextBox, but the user must be able to enter this TextBox and write at the end of earlier text, so I cannot make it ReadOnly or Enable = false.

I try to handle MouseDown and do the following:

input.Select(input.Text.Length, 0);

It helps with placing a cursor in the middle of text, but the user still can make a selection from the end.

I also make a MessageBox() on MouseDown event, but in this case the user cannot click on textBox and write anything.

The last try was to set a focus() in another Control and focus back, after a period of time, but it didn't work at all. User still can make a selection.

How can I do it?

like image 208
Pieniadz Avatar asked Sep 14 '11 17:09

Pieniadz


3 Answers

How about this for Click event

Edit: Also do the same for DoubleClick and MouseLeave to cover all cases. You can have a common event handler.

    private void textBox1_Click(object sender, EventArgs e)
    {
        ((TextBox) sender).SelectionLength = 0;
    }
like image 184
Bala R Avatar answered Sep 25 '22 06:09

Bala R


If it fits the UI/user model, another approach is to use two text boxes: a read-only one with the previous text that the user can see and act on (if that is something he needs to do) and an editable one for the new text along with a button to commit the new text to the read-only text box (and persistence layer).

That approach is not only arguably more user-friendly—the editable box is completely editable rather than just "appendable", which gets confusing when the user hits Backspace—but also requires less fighting with the framework to make the boxes do what you need.

like image 21
DocMax Avatar answered Sep 23 '22 06:09

DocMax


You're not far off with your MouseDown event handler, but probably better to catch MouseUp, as this is the event that will fire when they have finished selecting.

Alternatively, you could catch the SelectionChanged event.

Just put your:

input.Select(input.Text.Length, 0);

code in any of those event handlers.

like image 20
Chris Bampton Avatar answered Sep 23 '22 06:09

Chris Bampton