I did it myself, and that’s how I did it.
When the drop-down list opens, register the click event in the parent form of the control:
this.Form.Click += new EventHandler(CloseDropDown);
But it only takes halfway. You probably want your drop to also close when the current window is deactivated. The most reliable way to detect this for me was through a timer that checks which window is currently active:
[System.Runtime.InteropServices.DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
and
var timer = new Timer(); timer.Interval = 100; timer.Tick += (sender, args) => { IntPtr f = GetForegroundWindow(); if (this.Form == null || f != this.Form.Handle) { CloseDropDown(); } };
Of course, you should, of course, only start the timer when the drop-down image is visible. In addition, there may be several other events in the parent form that you want to register when you open the drop-down list:
this.Form.LocationChanged += new EventHandler(CloseDropDown); this.Form.SizeChanged += new EventHandler(CloseDropDown);
Do not forget to unregister all these events in the CloseDropDown method :)
EDIT:
I forgot, you should also register a Leave event on your control to see if another control is activated / activated:
this.Leave += new EventHandler(CloseDropDown);
I think I have it now, this should cover all the bases. Let me know if I missed something.
Kristoffer lindvall
source share