Omri Btian
Omri Btian

Reputation: 6547

How to catch Whitespace on TextBox prefore it occurs

I'm creating a custom control called SearchBox, which has a ControlTemplate with a textbox called searchTextBox.

I have a handlee for searchTextBox.TextChanged event that does some processing, but I want to have a different method that handles whitespace.

I can't use PreviewTextInput event as it is not fired on whitespace. I also tried handling PreviewKeyDown but it seems to have unpredictable behavior where sometimes it catches the whitespace and sometimes it doesn't.

How can I catch a whitespace before it occurs on a TextBox?

Upvotes: 0

Views: 1477

Answers (5)

Omri Btian
Omri Btian

Reputation: 6547

Thank you for your answers but non of the above actually worked for me. I ended up checking for the tailing character in the TextChanged event

if (Text.EndsWith(" "))
    HandleWhitespace();

Upvotes: 1

Björn
Björn

Reputation: 3418

Would it be possible to listen to the event PreviewKeyDown and do your processing there?

Edit 1: By using PreviewKeyDown you won't be able to process pasted text I guess.

Edit 2: In a project I have created a derived textbox which overrides the OnPreviewKeyDown:

protected override void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs e)
{
    base.OnPreviewKeyDown(e);
    if (e.Key == System.Windows.Input.Key.Space)
    {
        //Prevent spaces (space does not "raise" OnPreviewTextInput)
        e.Handled = true;
    }
}

In this case I did not want the textbox to do anything with space. Maybe you could do something similar? Maybe raise a custom event if there is a whitespace.

Upvotes: 0

huankfy
huankfy

Reputation: 1

As etaiso answered, you can assigned the KeyDown or PreviewKeyDown event. etaiso's answer is based on windows form not wpf. You can specifiy the e.Handle = ture instead of SuppressKeyPress

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Space)
    {
        e.Hanlded = true; // SuppressKeyPress is for windows form
    }
}

Upvotes: 0

Gusdor
Gusdor

Reputation: 14334

Try PreviewKeyDownas well as TextChanged.

Not all keys are captured in TextChanged. Backspace is a prime offender.

If you modify the text within either event handler, be sure to save and restore the current selection to the best of your ability. If you do not, the carat will always toggle to the start of the textbox and this is very annoying for users.

Why both?

Non-key operations like pasting and cutting text will not trigger PreviewKeyDown.

Upvotes: 0

etaiso
etaiso

Reputation: 2746

You can assign the KeyDown event and do something like:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Space)
    {
        // handle whitespace
    }
}

If you don't want to whitespace to appear on the textbox you can set e.SuppressKeyPress = true;

Upvotes: 0

Related Questions