2

MS Visual Studio 2010 で WPF アプリケーションを使用して電卓を作成しています。標準の電卓にあるさまざまなボタンを作成し、それらに button_Click メソッドを追加しました。ここで、特定のキーを押すことによって、button_Click メソッドが実行しているのと同じタスクも実行したいと考えています。

例えば

「addButton_Click」メソッドがあり、これを実行します:

    private void addButton_Click(object sender, RoutedEventArgs e)
    {
        _op = 1;    
        temp = displayPannel.Text;
        check = true;
    }

ここで、マウスを使用して「+」ボタンをクリックする代わりに、電卓で「+」キーを使用して同じことを行いたいとしたらどうでしょう。また、マウスのクリックと一緒にテンキーも使いたいです。どうすればいいですか?

4

2 に答える 2

2

MainWindow.xaml.cs

  private void TextBox_PreviewKeyUp_1(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.OemPlus || e.Key == Key.Add)
            MessageBox.Show("Tada");
    }

MainWindow.xaml

    <TextBox Text="Hello" PreviewKeyUp="TextBox_PreviewKeyUp_1"/>
于 2012-08-05T21:05:45.287 に答える
2

You should extract method that does Add operation. It's not mandatory, but it's a good practice to call methods from handers, instead of having some large code inside handler, for example:

    private void addButton_Click(object sender, RoutedEventArgs e)
    {
        PerformAdd();
    }

    private void PerformAdd()
    {
        _op = 1;
        temp = displayPannel.Text;
        check = true;
    }

And Your actual question(I'm assuming here You want to create something like Windows Calculator):

  1. Attach handler for PreviewKeyDown in MainWindow.xaml. It's preferable to use PreviewKeyDown, not KeyDown in Your case, as Preview events go from "outside to inside", meaning event will show up in MainWindow handler first, then in handlers for controls inside MainWindow, while normal events show up in inner classes first. Catching event in MainWindow first will allow You to process keypresses like '+' or '-' globally, without passing them to inner controls.

  2. In handler You should check KeyCode, and call appropriate method, like this:

     private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
             {
                 if (e.Key == Key.OemPlus || e.Key == Key.Add)
                 {
                     PerformAdd();
                     e.Handled = true;
                 }
             }
    

As You can see there is e.Handled = true; line. If You mark event as handled it won't be passed to inner controls. You should mark it handled for 'operations' key presses, these keypresses shouldn't be passed as input to text box.

EDIT: As for numbers, You can do:

 if (e.Key == Key.D0 || e.Key == Key.NumPad0)
      textBox.Text = textBox.Text + "0";
于 2012-08-05T21:33:41.490 に答える