Search code examples
c#winformstextbox

How to append a non-breaking space in a TextBox?


I have a WinForms project where I am entering Persian text into a TextBox control. I have seen   usage in HMTL pages. However what I need here is I want to set a keyboard shortcut so when the shortcut key is pressed, the TextBox appends a non-breaking space to the text and the user can continue entering the rest. This element,  , really matters for some languages like Persian as you could see in the following:

Normal Text:

کتابخانه های الکترونیکی

With Non-breaking Space :

کتابخانه‌های الکترونیکی

How can I use that in WinForms?


Solution

  • You can catch the KeyPress event and insert the character you want at the insertion point like this:

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)Keys.Space &&
            ModifierKeys == Keys.Control)
        {
            char nbrsp = '\u2007';                 // non-breaking space
            char zerospace = '\u200B';            // zero space
            char zerospacenobinding = '\u200C';  //zero space no character binding
            char zerospacebinding = '\u200D';   // zero space with character binding
    
            int s = textBox1.SelectionStart;
            textBox1.Text = textBox1.Text.Insert(s, nbrsp.ToString() );
            e.Handled = true;
            textBox1.SelectionStart = s + 1;
        }
    }
    

    Note that while Word uses I Ctl-Shift-Spacethis combination also may switch between Right-To-Left and Left-To-Right. So let's use Ctrl-Space insteadt.

    Also note that while KeyDown does have an e.Handled parameter, setting it to true does not suppress the character that was entered. So we need to use the KeyPress event..