我想在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);
}
問我是否需要其他代碼可以看到。
- 按
2
從鍵盤數字鍵盤 - 點擊
+
- 按
1
從鍵盤小鍵盤(你不會看到1進來的文本框) - Click等於
我試圖重建你的問題(與Form.KeyDown),但我沒有得到你的問題。 – Mitja
那麼爲什麼'KeyDown'?我重寫了'ProcessCmdKey'方法。 –