简体   繁体   中英

c# Listbox control (arrows and enter keys)

I have a listbox which displays the contents of an array. The array is populated with a list of results when my "go" button is pressed.

The go button is set as the AcceptButton on the form properties so pressing the Enter key anywhere in the focus of the form re-runs the go button process.

Double clicking on a result from the array within the listbox works fine using below:

void ListBox1_DoubleClick(object sender, EventArgs e) {}

I would like to be able to use my arrow keys and enter keys to select and run an event without having to double click on the line within the listbox. (however go button runs each time instead)

Basically open the form, type search string, press enter to run go button, use up and down arrows then press enter on selection to run same event as double click above. Will need to change focus after each bit.

You can handle the KeyDown events for the controls you want to override. For example,

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        //execute go button method
        GoButtonMethod();
        //or if it's an event handler (should be a method)
        GoButton_Click(null,null);
    }

}

That will perform the search. You can then focus your listbox

myListBox.Focus();
//you might need to select one value to allow arrow keys
myListBox.SelectedIndex = 0;

You can handle the Enter button in the ListBox the same way as the TextBox above and call the DoubleClick event.

This problem is similar to - Pressing Enter Key will Add the Selected Item From ListBox to RichTextBox

Certain controls do not recognize some keys when they are pressed in Control::KeyDown event. For eg list box does not recognize if the key pressed is Enter key.

See the remarks section of the Control::KeyDown event reference.

One way to resolve your problem might be writing a method for the Control::PreviewKeyDown event for your list box control:

private void listBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Up && this.listBox1.SelectedIndex - 1 > -1)
    {
        //listBox1.SelectedIndex--;
    }
    if (e.KeyCode == Keys.Down && this.listBox1.SelectedIndex + 1 < this.listBox1.Items.Count)
    {
        //listBox1.SelectedIndex++;
    }
    if (e.KeyCode == Keys.Enter)
    {
        //Do your task here :)
    }
}

private void listBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.Enter:
            e.IsInputKey = true;
            break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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