Textbox SelectAll on tab but not mouse click

后端 未结 5 929
情深已故
情深已故 2021-01-07 22:56

So lets say I have a WPF form with several text boxes, if you tab to the text box and it already has something in it, I want to select all the text in that box so typing wil

5条回答
  •  佛祖请我去吃肉
    2021-01-07 23:24

    You could capture the last key pressed and compare against it in your event

    private Key lastKey;
    protected override void OnKeyDown(KeyEventArgs e)
    {
         lastKey = e.Key;
         base.OnKeyDown(e);
    }
    

    and in your event:

    private void EventSetter_OnHandler(object sender, RoutedEventArgs e)
    {
        if(lastKey != Key.Tab)
            return;
    
        TextBox txt = sender as TextBox;
        if (txt != null) txt.SelectAll();
    }
    

    It's not perfect because they could have hit tab (not tabbing into your control) and than click into it your control. But it will work most of the time.

提交回复
热议问题