Stopbyte

How to intercept ListBox ItemSelection in C# WindowsForms for specific items?

Hi,

Is it possible to intercept the ItemSelection functionality of a Windows Forms ListBox?!

I am currently doing it like this:

int old_selected_index = 0;
protected override void OnSelectedIndexChanged(EventArgs e)
{
    string str = listBox1.SelectedItem.ToString();
    int new_index = listBox1.SelectedIndex;
    if (str == "" )
    {
        if (new_index > old_selected_index && new_index  < listBox1.Items.Count)
        {
            listBox1.SelectedIndex++;
        }
        else if (new_index < old_selected_index && new_index > 0)
        {
            listBox1.SelectedIndex--;
        }
    }
    else old_selected_index = new_index;
}

The problem with the code above is it causes for the ListBox To flicker :confused: it shows the new item selected and then goes back to the old one.

Is there a more genuine way?

2 Likes

Maybe you should override the WndProc() and handle MouseDown Windows Message WM_MOUSEDOWN the way you need.