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

編譯並執行上述程式碼後,將生成以下視窗 −

Output of Keyword

如果你在文字框內單擊“Open”按鈕或按 CTRL+O 鍵,它將顯示相同的訊息。

Click on Open button
wpf_input.htm
廣告