WPF - 键盘

键盘输入有很多种类型,如KeyDown、KeyUp、TextInput等。下面的示例中处理了部分键盘输入。 以下示例定义了 Click 事件的处理程序和 KeyDown 事件的处理程序。

  • 让我们创建一个名为 WPFKeyboardInput 的新 WPF 项目。

  • 将文本框和按钮拖动到堆栈面板,并设置以下属性和事件,如以下 XAML 文件中所示。

<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> 

下面是处理不同键盘和单击事件的 C# 代码。

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?"); 
      }
		
   } 
}

上面的代码编译执行后,会产生如下窗口−

关键字输出

如果单击"打开"按钮或在文本框中按 CTRL+O 键,它将显示相同的消息。

单击打开按钮

❮ wpf_input.html