D
D
Daniel2017-07-29 10:48:33
.NET
Daniel, 2017-07-29 10:48:33

How to cancel the focus response in a ListBox when a key is pressed?

There is a form on which the main elements are a ListBox, a search bar and a ComboBox (for selecting sections).
When data is received from the Internet, the ListBox is filled with several hundred values, and interaction with these values ​​(more precisely, with indexes of values) is carried out using key combinations (listData_KeyDown Event). For example, there are 5 elements in the list: 1, 2, 3, 4, 5. When selecting the required element with the arrows or the mouse, press Ctrl + D, then take the index of the selected element and already interact with the element from the internal list at this index. But here an unpleasant situation arises when, for example, we have several hundred lines that begin with different letters / symbols / numbers, and when you press Ctrl + D, if the list contains a line starting with the letter D, then regardless of whether which line was selected, the focus jumps to the line with the letter D at the beginning.
Although the action is performed with the element on which the key combination was pressed, it’s somehow wrong to see that the focus flies every time from the desired line to the wrong one.
I've tried returning focus back to the selected row by setting the listData.SelectedIndex property to the index of the row, also by calling the listData.SetSelected() method, but it often happens that the user sees the focus flicker and scroll through the list when he first flies to the row with the first letter keys, and then returns.
How can I cancel the focus response in a ListBox when a key combination is pressed? So that it does not fly to the line with the first letter of the key? Maybe there is some solution out of the box that would allow you to disable such a ListBox reaction. I will be grateful for answers.
Windows Forms Project, Visual Studio 2017 Community.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
rFczZZ, 2017-07-29
@Dyaminigo

private void listBox1_KeyDown(object sender, KeyEventArgs e)
{
    // для всех нужных сочетаний клавиш
    if (e.Modifiers == Keys.Control)
    {
        listBox1.Items[listBox1.SelectedIndex] = $"{listBox1.SelectedItem} !!!";

        // нужно установить флаг SuppressKeyPress, 
        // чтобы сообщение не обрабатывалось дальше
        e.SuppressKeyPress = true;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question