简体   繁体   English

如何捕获ListBox控件中的Enter键?

[英]How to capture Enter key in a ListBox control?

I read articles over the internet but I think I'm missing something here. 我在互联网上阅读过文章,但我想这里缺少一些东西。 I tried following the answer to this SO question , but nothing has happened. 我尝试遵循此SO问题的答案,但未发生任何反应。

I wanted to trigger the usePort_Click method whenever I press the Enter/Return key. 每当我按下Enter / Return键时,我都想触发usePort_Click方法。 Also, I don't know how to get around the EventArgs parameter of usePort_Click whenever I do try calling it from the ports_Keydown method. 另外,当我尝试从ports_Keydown方法调用它时,我也不知道该如何解决usePort_Click的EventArgs参数。

Note: ports is a ListBox control. 注意: ports是一个ListBox控件。

    private void usePort_Click(object sender, EventArgs e)
    {
        try
        {
            port = new SerialPort((string)ports.SelectedItem, 9600);
            portUsedLabel.Text = (string)ports.SelectedItem;

            String buffer = "";
            String tellArduino = "food";    // test value

            port.Open();
            port.WriteLine(tellArduino);

            for (int x = 0; x < tellArduino.Length; x++)
            {
                buffer += port.ReadLine();
            }

            ports.Items.Add(buffer);
            port.Close();
        }
        catch { //stuff }
    }

    private void ports_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            //code here
        }
    }

A good solution would be to move the code you want to execute into a separate method (I called it someStuff , replace the name with something better) and call that method from both event handlers: 一个好的解决方案是将要执行的代码移到一个单独的方法中(我称其为someStuff ,用更好的名称替换名称),然后从两个事件处理程序中调用该方法:

private void usePort_Click(object sender, EventArgs e)
{
    someStuff();
}

private void ports_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        someStuff();
    }
}

private void someStuff()
{
    try
    {
        port = new SerialPort((string)ports.SelectedItem, 9600);
        portUsedLabel.Text = (string)ports.SelectedItem;

        String buffer = "";
        String tellArduino = "food";    // test value

        port.Open();
        port.WriteLine(tellArduino);

        for (int x = 0; x < tellArduino.Length; x++)
        {
            buffer += port.ReadLine();
        }

        ports.Items.Add(buffer);
        port.Close();
    }
    catch { //stuff }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM