WPF - Clavier

Il existe de nombreux types d'entrées clavier telles que KeyDown, KeyUp, TextInput, etc. Dans l'exemple suivant, certaines des entrées clavier sont gérées. L'exemple suivant définit un gestionnaire pour l'événement Click et un gestionnaire pour l'événement KeyDown.

  • Créons un nouveau projet WPF avec le nom WPFKeyboardInput.

  • Faites glisser une zone de texte et un bouton vers un panneau de pile et définissez les propriétés et événements suivants comme indiqué dans le fichier XAML suivant.

<Window x:Class = "WPFKeyboardInput.MainWindow" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:local = "clr-namespace:WPFKeyboardInput" 
   mc:Ignorable = "d" Title = "MainWindow" Height = "350" Width = "604"> 
	
   <Grid> 
      <StackPanel Orientation = "Horizontal" KeyDown = "OnTextInputKeyDown"> 
         <TextBox Width = "400" Height = "30" Margin = "10"/> 
         <Button Click = "OnTextInputButtonClick"
            Content = "Open" Margin = "10" Width = "50" Height = "30"/> 
      </StackPanel> 
   </Grid> 
	
</Window>

Voici le code C # dans lequel différents événements de clavier et de clic sont gérés.

using System.Windows; 
using System.Windows.Input; 

namespace WPFKeyboardInput { 
   /// <summary> 
      /// Interaction logic for MainWindow.xaml 
   /// </summary> 
	
   public partial class MainWindow : Window { 
	
      public MainWindow() { 
         InitializeComponent(); 
      } 
		
      private void OnTextInputKeyDown(object sender, KeyEventArgs e) {
		
         if (e.Key == Key.O && Keyboard.Modifiers == ModifierKeys.Control) { 
            handle(); 
            e.Handled = true; 
         } 
			
      } 
		
      private void OnTextInputButtonClick(object sender, RoutedEventArgs e) { 
         handle(); 
         e.Handled = true; 
      } 
		
      public void handle() { 
         MessageBox.Show("Do you want to open a file?"); 
      }
		
   } 
}

Lorsque le code ci-dessus est compilé et exécuté, il produira la fenêtre suivante -

Si vous cliquez sur le bouton Ouvrir ou appuyez sur les touches CTRL + O dans la zone de texte, le même message s'affichera.