0

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.

I wanted to trigger the usePort_Click method whenever I press the Enter/Return key. 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.

Note: ports is a ListBox control.

    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
        }
    }
Community
  • 1
  • 1
Nogurenn
  • 858
  • 3
  • 11
  • 28

1 Answers1

0

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:

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 }
}
Szymon
  • 42,577
  • 16
  • 96
  • 114
  • 1
    Ah, there! This solution would also eliminate the trouble of manipulating KeyEventArgs and EventArgs, right? It was my main trouble. – Nogurenn Nov 03 '13 at 06:45
  • Yes, that's right. You're not using those event args so it makes it simple. – Szymon Nov 03 '13 at 06:53