How to put a combo box into a Popup and prevent the dropdown from closing when clicked on it?
Normally, when you put a combo box into a popup, the popup will be hidden when you click on the combo box drop-down. This is because the popup framework expects the windows you activate to be .NET control based, otherwise it just gives up.
To work around this problem, use a custom PopupControlContainer, as follows. Check out the inline comments.
C#
public class CustomPopupControlContainer : PopupControlContainer
{
public CustomPopupControlContainer()
{
}
public CustomPopupControlContainer(IContainer container):this()
{
container.Add(this);
}
public override bool IsRelatedControl ( System.Windows.Forms.Control control , System.Boolean askPopupParent )
{
bool isrelated = base.IsRelatedControl(control, askPopupParent);
// This will be the case when native windows without dotnet wrappers are encountered
// like the combo box dropdown.
if(control == null && !isrelated)
{
// If so, then go ahead and get a dotnet parent control.
IntPtr hwnd = GetFocus();
// This method goes up the hierarchy looking for a dotnet parent.
Control dotnetParent = PopupUtils.GetADotNetParentControl(hwnd);
if(dotnetParent != null)
// if found then check if that is a related control, instead.
isrelated |= base.IsRelatedControl(dotnetParent, askPopupParent);
}
return isrelated;
}
[DllImport("user32.dll", CharSet=CharSet.Auto, CallingConvention=CallingConvention.Winapi)]
public static extern IntPtr GetFocus();
[DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true, CallingConvention=CallingConvention.Winapi)]
public static extern IntPtr GetParent(IntPtr hwnd);}