Permanent prefix in a TextBox

c#, winforms

Solution

Using the KISS principle is indicated here. Trying to catch key presses just won't do anything when the user uses Ctrl+V or the context menu's Cut and Paste commands. Simply restore the text when anything happened that fudged the prefix:

    private const string textPrefix = @"DOMAIN\";

    private void textBox1_TextChanged(object sender, EventArgs e) {
        if (!textBox1.Text.StartsWith(textPrefix)) {
            textBox1.Text = textPrefix;
            textBox1.SelectionStart = textBox1.Text.Length;
        }
    }

And help the user avoid editing the prefix by accident:

    private void textBox1_Enter(object sender, EventArgs e) {
        textBox1.SelectionStart = textBox1.Text.Length;
    }

Problem

I am trying to have a permanent prefix input in the textbox. In my case, I want to have the following prefix: `DOMAIN\` So that users can only have to type their username after the domain prefix. It's not something I have to do, or pursue but my question is more out of curiosity. I was trying to come up with some logic to do this on the `TextChangedEvent` however, this means I need to know which characters have been deleted where and then pre-append `DOMAIN\` to whatever their input is - I can't work out the logic for this so I can't post what I have tried apart from where I got to. ``` public void TextBox1_TextChanged(object sender, EventArgs e) { if(!TextBox1.Text.Contains(@"DOMAIN\") { //Handle putting Domain in here along with the text that would be determined as the username } } ``` I've looked on the internet and can't find anything, How do I have text in a winforms textbox be prefixed with unchangable text? was trying to do a similar thing but the answers don't really help. Any ideas on how I can keep the prefix `DOMAIN\` in a `TextBox`?

Original source