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.
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();
}
}