2014-12-25 15 views
0

我想在C#的Windows窗體應用程序中建立一個正常的計算器。我想,當我按任何數字鍵時,數字將顯示在文本框中,就像在任何標準計算器中發生的一樣。如何在計算器窗體表單應用程序中正確使用ProcessCmdKey?

所以從研究我得到這可以通過覆蓋ProcessCmdKey和更改KeyPreview財產的形式爲true

問題是:當我完全使用數字鍵盤時,計算器工作正常。但是,當我結合鼠標點擊任意數字按鈕,然後嘗試再次使用數字鍵時,數字不會顯示在TextBox中。

我有數字鍵(將火0-9所有按鈕點擊)的通用上單擊的方式

private void number_button_Click(object sender, EventArgs e) 
{ 
    Button button = (Button)sender; 
    textBox1.Text = textBox1.Text + "" + button.Text; 
} 

Add方法(如減法,除法,乘法明智的方法)

private void buttonPlusClk_Click(object sender, EventArgs e) 
{ 
    sign = "+"; 
    operandOne = double.Parse(textBox1.Text); 
    textBox1.Text = ""; 
} 

對於表格

this.KeyPreview = true; 

的重寫ProcessCmdKey方法

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
{ 
    if (keyData == (Keys.NumPad0 | 
     Keys.NumPad1 | 
     Keys.NumPad2 | 
     Keys.NumPad3 | 
     Keys.NumPad4 | 
     Keys.NumPad5 | 
     Keys.NumPad6 | 
     Keys.NumPad7 | 
     Keys.NumPad8 | 
     Keys.NumPad9)) 
    { 

     // also not sure about the KeyEventArgs(keyData)... is it ok? 
     number_button_Click(keyData, new KeyEventArgs(keyData)); 
     return true; 

    } 
    else if(keyData == (Keys.Add)) 
    { 
     buttonPlusClk_Click(keyData, new KeyEventArgs(keyData)); 
     return true; 
    } 
    // ... and the if conditions for other operators 
    return base.ProcessCmdKey(ref msg, keyData); 
} 

問我是否需要其他代碼可以看到。


以供將來參考拿到SSCCEGitHub和重建問題做

  1. 2從鍵盤數字鍵盤
  2. 點擊+
  3. 1從鍵盤小鍵盤(你不會看到1進來的文本框)
  4. Click等於
+0

我試圖重建你的問題(與Form.KeyDown),但我沒有得到你的問題。 – Mitja

+0

那麼爲什麼'KeyDown'?我重寫了'ProcessCmdKey'方法。 –

回答

1

在您的密鑰處理函數中試試這個。當它們不被用作標誌時,異或號碼是不正確的。
此外,從該函數調用事件處理程序會導致錯誤,因爲第一個參數不是按鈕。

 protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
     { 
      int intKey = (int)keyData; 
      if (intKey >= 96 && intKey <= 105) // 96 = 0, 97 = 1, ..., 105 = 9 
      { 
       textBox1.Text = textBox1.Text + (intKey - 96).ToString(); 
       return true; 

      } 
      // ... and the if conditions for other operators 
      return base.ProcessCmdKey(ref msg, keyData); 
     } 
+0

非常感謝。你能否詳細說明*「異或數字在不作爲標誌使用時是不正確的」*有點? –

+0

如果您查看'Keys'的二進制表示形式,您會看到:Keys.NumPad0 => 0110 0000 Keys.NumPad1 => 0110 0001 Keys.NumPad2 => 0110 0010 當您應用XOR(單管)對這些,那麼你在這些字節中的每一位)你最終與0110 0011,這是Keys.NumPad3。 –

+0

對所有數字鍵進行XOR運算,得到整數111,這是鍵'分界線'。您可以使用'Keys result =(Keys.NumPad0 | Keys.NumPad1 | Keys.NumPad2 | Keys.NumPad3 | Keys.NumPad4 | Keys.NumPad5 | Keys.NumPad6 | Keys.NumPad7 | Keys.NumPad8 | Keys |NUMPAD9);'。所以,按分隔鍵會進入你的初始if。 –

相關問題