Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make TextBox lose its focus?

How to make TextBox lose its focus and hide onscreen keyboard when user touches Enter virtual key?

    private void TheName_KeyDown(object sender, KeyRoutedEventArgs e) {
        var tb = sender as TextBox;
        if (e.Key == Windows.System.VirtualKey.Enter) {
            // ... tb.LooseTheFocus_PLEASE(); !???
        }
    }
like image 702
Harry Avatar asked Jun 16 '14 20:06

Harry


2 Answers

    /// <summary>
    /// Makes virtual keyboard disappear
    /// </summary>
    /// <param name="sender"></param>
    private void LoseFocus(object sender) {
        var control = sender as Control;
        var isTabStop = control.IsTabStop;
        control.IsTabStop = false;
        control.IsEnabled = false;
        control.IsEnabled = true;
        control.IsTabStop = isTabStop;
    }

    /// <summary>
    /// Makes virtual keyboard disappear when user taps enter key
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void LooseFocusOnEnter(object sender, KeyRoutedEventArgs e) {
        if (e.Key == Windows.System.VirtualKey.Enter) {
            e.Handled = true; LoseFocus(sender);
        }
    }

It's ugly. But it works. The key part is IsTabStop property. If I don't touch it - the keyboard disappers for a fraction of a second and reapears again.

like image 144
Harry Avatar answered Sep 23 '22 18:09

Harry


Just set the focus to the page.

this.Focus();
like image 35
Pantelis Avatar answered Sep 23 '22 18:09

Pantelis