简体   繁体   中英

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?

You can handle KeyPress event and then for example if the user pressed Ctrl + Space , replace the space with a \​ character:

using System.Windows.Forms;
public class ExTextBox : TextBox
{
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        if(e.KeyChar==' ' && ModifierKeys== Keys.Control)
            e.KeyChar='\u200B';
        base.OnKeyPress(e);
    }
}

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-Space this 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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM