Wpf-keyboard

提供:Dev Guides
移動先:案内検索

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キーを押すと、同じメッセージが表示されます。

開くボタンをクリック