Textbox SelectAll on tab but not mouse click

后端 未结 5 911
情深已故
情深已故 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:30

    You could try checking if the Mouse is present in the TextBox when the Focus Event happens and check the Mouse ButtonButtonState. This is not perfect but should be close to what you are looking for.

    private void EventSetter_OnHandler(object sender, RoutedEventArgs e)
    {
        TextBox txt = sender as TextBox;
        Point position = Mouse.GetPosition(txt);
        // if Mouse position is not in the TextBox Client Rectangle
        // and Mouse Button not Pressed.
        if((!(new Rect(0,0,txt.Width,txt.Height)).Contains(position)) || ( Mouse.LeftButton != MouseButtonState.Pressed))
            if (txt != null) txt.SelectAll();
    }
    

    and as H.B. Pointed out you could try using the txt.IsMouseOver Property to determine if the Cursor is inside the TextBox's Client Rectangle. It looks a lot cleaner.

    private void EventSetter_OnHandler(object sender, RoutedEventArgs e)
    {
        TextBox txt = sender as TextBox;
        if( !txt.IsMouseOver || Mouse.LeftButton != MouseButtonState.Pressed)
            if (txt != null) txt.SelectAll();
    }
    

提交回复
热议问题