KeyPress event equivalent in WPF

后端 未结 3 1863
广开言路
广开言路 2020-12-29 05:19

i have the following code in WPA, and i am trying to convert it to WPF. I tried Keydown instead of Keypress and changed, for example,

(e.keyChar == \'-\')          


        
相关标签:
3条回答
  • 2020-12-29 05:53

    You're looking for the TextInput event, or perhaps PreviewTextInput.

    The EventArgs type is TextCompositionEventArgs; I believe you want the Text property here, but I'm not at all sure of that.

    0 讨论(0)
  • 2020-12-29 05:53
    <TextBox x:Name="txtbx" KeyDown="OnKeyDownHandler" Height="23" Width="250">
    </TextBox>
    
    private void OnKeyDownHandler(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Return)
        {
            txtbx.Text = "You Entered: " + txtbx.Text;
        }
    }
    
    0 讨论(0)
  • 2020-12-29 06:00

    It's very similar - but you compare e.Key to the Key enumeration.

    Register your event handler somewhere (such as the constructor, or window_loaded):

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this.KeyDown += new KeyEventHandler(MainWindow_KeyDown);
    }
    

    And then in the event handler:

    void MainWindow_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Subtract)
        {
            // Do something
        }
    }
    
    0 讨论(0)
提交回复
热议问题