什么传递给检查键是否被按下的方法?

问题描述:

好吧,我创建了一个名为KeyCheck()的方法,它应该检查一个按键是否被按下(具体来说就是回车键),如果是,它会按button1什么传递给检查键是否被按下的方法?

不幸的是,当我调用该方法时,我不确定要传递给它的方法。我希望它知道何时按下回车键。

public partial class Form1 : Form 
{ 
    public void GameStart() 
    { 
     richTextBox1.WordWrap = true; 
     richTextBox1.SelectionAlignment = HorizontalAlignment.Center; 
     richTextBox1.Text = "Hello, Welcome to Grandar!"; 
    } 

    public Form1() 
    { 
     InitializeComponent(); 
     GameStart(); 
     //What variable do I pass to KeyCheck Method? 
     KeyCheck(); 
    } 

    private void KeyCheck(KeyPressEventArgs k) 
    { 
     if (k.KeyChar == (char)Keys.Enter) 
     { 
      button1.PerformClick(); 
     } 
    } 

    private void richTextBox1_TextChanged(object sender, EventArgs e) 
    { 

    } 

    private void button1_Click(object sender, EventArgs e) 
    { 

    } 
} 

的东西夫妇这里要注意:

一)你真要直接调用KeyCheck作为示例代码提示,还是应该进行布线的形式处理程序(其中信息你所要求的将被自动提供 - 需要改变签名以符合标准处理程序,就像你在其他一些方法中一样)。

B)我不认为你可以调用KeyCheck方法就像你正在做的,除非你挂钩另一个事件来捕获键击,然后将它传递给该方法,通过newing了new KeyPressEvent(...)

因此,要回答你的问题,我想你会想是这样(伪代码)

public Form1() 
{ 
    InitializeComponent(); 
    GameStart(); 

    // Wire up a handler for the KeyPress event 
    this.KeyPress += KeyCheck; 
} 

private void KeyCheck(object sender, KeyPressEventArgs e) 
{ 
    if (e.KeyChar == (char)Keys.Enter) 
    { 
     button1.PerformClick(); 
    } 
} 
+0

谢谢您的回答。 – user3751027 2015-02-07 23:39:58

看看这个页面:https://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=vs.110).aspx

你会想类似的其他方法的东西,与发送方对象和事件参数。

if (e.KeyCode < Keys.Enter) { 
    //Your logic 
} 

订阅此:

this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.KeyPress_Method); 

以及检查Enter键的方法:

void KeyPress_Method(object sender, KeyPressEventArgs e) 
{ 
    if (e.KeyChar == (char)13) // enter key 
    { 
     // your code 
    } 
} 
+0

谢谢你的回答。 – user3751027 2015-02-07 23:40:13