Search code examples
c#winformscomboboxmouseeventonmouseover

WinForms - Disable default mouse hover over item behaviour?


I have a ComboBox with items in it. I also have a SelectedIndexChange event. When I open the ComboBox and hover over an item, the SelectedIndex property seems to change to that item. I'd only like it to change when I click on the item. Is it possible to disable that behavior?

I have a timer that refreshes an Image based on SelectedIndex of ComboBox, but still, even if I highlight an item but don't select, why does the Image changes while it should not change and it only should change when I select an item.


Solution

  • The Problem

    When the the mouse moves on items of ComboBox, the SelectedIndex changes but SelectedIndexChanged event doesn't fire, so in your timer Tick event, you will see the change while SelectedIndexChanged doesn't fire.

    Scenario of reproducing the problem

    To simply reproduce the problem, put a Timer on a form and enable it, then handle its Tick event. Also add a ComboBox and add some items to it and handle its SelectedIndexChanged event. When you open the dropdown and move mouse over items, you will see the Text of form changes to the index of item that is under the cursor, while SelectedIndexChanged doesn't fire and no MessageBox will show.

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        MessageBox.Show(this.comboBox1.SelectedIndex.ToString());
    }
    
    private void timer1_Tick(object sender, EventArgs e)
    {
        this.Text = this.comboBox1.SelectedIndex.ToString();
    }
    

    The Solution for your case

    You can simply check if the dropdown is not open using DroppedDown property of ComboBox, then do the job:

    private void timer1_Tick(object sender, EventArgs e)
    {
        if(!this.comboBox1.DroppedDown)
            this.Text = this.comboBox1.SelectedIndex.ToString();
    }