1 回答

TA貢獻2011條經驗 獲得超2個贊
更新答案
由于您仍然有問題,您必須做的是刪除以前的代碼并使用以下代碼。
//Have your form's KeyPress event like this, replace textBox1 with the name of your textbox
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
switch (e.KeyChar)
{
case '0':
textBox1.Text += "0";
break;
case '1':
textBox1.Text += "1";
break;
case '2':
textBox1.Text += "2";
break;
case '3':
textBox1.Text += "3";
break;
case '4':
textBox1.Text += "4";
break;
case '5':
textBox1.Text += "5";
break;
case '6':
textBox1.Text += "6";
break;
case '7':
textBox1.Text += "7";
break;
case '8':
textBox1.Text += "8";
break;
case '9':
textBox1.Text += "9";
break;
case '.':
textBox1.Text += ".";
break;
}
e.Handled = true;
}
有這樣的表單加載事件。
private void Form1_Load(object sender, EventArgs e)
{
this.KeyPreview = true;
}
舊答案
您需要做的是在您的表單上創建 KeyPress 事件,如下所示。
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '1')
{
btn1_Click(null, null);
}
else if (e.KeyChar == '2')
{
btn2_Click(null, null);
}
//Go write your code with else if.........
}
然后,當您想在窗體中的任何位置捕獲 KeyPress 事件時,下面的代碼會將上述 KeyPress 事件添加到窗體上的所有控件,以便您可以在窗體中的任何位置捕獲 KeyPress 事件。
private void Form1_Load(object sender, EventArgs e)
{
foreach (Control ctrl in Controls)
{
ctrl.KeyPress += Form1_KeyPress;
}
}
正如@Rufus L 在他的回答中提到的,您可以只使用 KeyPreview 屬性,該屬性將在實際控件接收到以下代碼之前捕獲其他控件的 KeyPress 事件。
private void Form1_Load(object sender, EventArgs e)
{
this.KeyPreview = true;
}
- 1 回答
- 0 關注
- 169 瀏覽
添加回答
舉報