Equivalent to a keypreview property in WPF

﹥>﹥吖頭↗ 提交于 2019-11-30 19:37:46

use the override in your own UserControls or Controls (this is an override from UIElement)

protected override void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs e) {
     base.OnPreviewKeyDown(e);
  }

if you want to preview the key down on any element which you dont create you can do this:

 Label label = new Label();
 label.PreviewKeyDown += new KeyEventHandler(label_PreviewKeyDown);

and then have a handler like so :-

  void label_PreviewKeyDown(object sender, KeyEventArgs e) {

  }

if you mark the event as handled (e.Handled = true;) this will stop the KeyDown event being raised.

WPF uses event bubbling and tunneling. In other words the events travel down and up the visual element tree. Some events will have a corresponding Preview event. So MouseDown will have a PreviewMouseDown that you can respond to. Check out this link and scroll down to the WPF Input Events section.

Henry Skoglund

Thanks got it working! Only problem was I'm coding in VB not C#, but the basic idea holds. Neat to create a label out of thin air and use it to insert yourself in the event stream.

If someone else is interested of the same solution but in VB for WPF, here's my test program, it manages to toss all 'a' characters typed, no matter what control has the focus:

Class MainWindow

    Dim WithEvents labelFromThinAir As Label

    Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        AddHandler MainWindow.PreviewKeyDown, AddressOf labelFromThinAir_PreviewKeyDown
    End Sub

    Private Sub labelFromThinAir_PreviewKeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
        TextBox1.Text = e.Key    ' watch 'em coming
        If (44 = e.Key) Then e.Handled = True
    End Sub

End Class

P.S. This was my first post on stackoverflow, really a useful site. Perhaps I'll be able to answer some questions in here myself later on :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!