Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / Win32

Custom combobox dropdown Close Problem

0.00/5 (No votes)
2 Sep 2014CPOL1 min read 14.8K  
A simple solution to rolling up a Custom ComboBox list on mouse leave.

I've written a couple of custom WinForms controls with drop down lists before and ran across a problem of how to close the list when the mouse leaves the control area. I Googled a lot and read about global hooks and all kinds of kinky solutions but I think I've found a simple, maybe not elegant solution but it certainly works.

The custom ComboBox I've created here is comprised of a Button and a ListBox and the problem I was having was I could use the ListBox.OnMouseLeave event and rollup the ListBox but when I leave the button using the Button.OnMouseLeave, the ListBox would rolldown when I clicked on the button but rollup when I left the button even when in the ListBox area. The solution I've found tracks the mouse entering and leaving the Button and ListBox and when leaving the ListBox I rollup the control as I was doing but when I leave the button I set a timer and at the end of the tick if I'm not in the Button area or the ListBox area, I rollup the ListBox and stop the timer. If I am still in one of those areas, I reset the timer and do it again.

C#
//==============================================================================================
// NOTE The listbox closes when the mouse leaves the listbox area but wasn't closing when
// the mouse left the button area and I couldn't figure how to do it until now.
// I solved the problem of the control not collapsing the listbox when leaving the button by
// setting a timer when the mouse leaves the button and at end of timer tick if the mouse is
// not in the button area and not in the listbox are then closed.
//==============================================================================================
private void btnDropDown_MouseEnter(object sender, EventArgs e)
{
     _inButton = true;
}        

private void btnDropDown_MouseLeave(object sender, EventArgs e)
{
     _inButton = false;
     if (_isExtended)
       timer1.Start();
}        

private void dataGridView1_MouseEnter(object sender, EventArgs e)
{
      _inList = true;
}        

private void dataGridView1_MouseLeave(object sender, EventArgs e)
{
       _inList = false;
       _inButton = false;
       HandleExtendState(CustomComboBoxExtendState.collapse);
       timer1.Stop();
}       

private void timer1_Tick(object sender, EventArgs e)
{
       if (!_inList)
       {
           if (!_inButton)
           {
               timer1.Stop();
               HandleExtendState(CustomComboBoxExtendState.collapse);
            }
            else
               timer1.Start();
        }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)