Introduction
If you have an app where you use the selection of an item in a combobox
to trigger a possibly long operation, it can be annoying to the user that
the combo's list remains visible until the operation is complete. The code
shown in this article will hide the list as soon as the user clicks
to select a new item in the list.
Use
To use the code you will need to have your own override of CComboBox
.
I will assume you will already have one, or can make one. In the code the combo class is
CMyComboBox
.
In your override of CComboBox
, add a new virtual
function OnChildNotify
.
Then paste in the code below:
BOOL CMyComboBox::OnChildNotify(UINT message,
WPARAM wParam, LPARAM lParam, LRESULT* pLResult)
{
if (message == WM_COMMAND && (HWND)lParam == GetSafeHwnd())
{
if (HIWORD(wParam) == CBN_SELENDOK)
{
if (GetStyle() & CBS_DROPDOWN)
{
int nIndex = GetCurSel();
if (nIndex != -1)
{
CString sText;
GetLBText(nIndex, sText);
SetWindowText(sText);
}
}
ShowDropDown(FALSE);
}
}
return CComboBox::OnChildNotify(message,
wParam, lParam, pLResult);
}
This causes the drop-down list to be hidden when the combo receives a
CBN_SELENDOK
notification. In addition to closing the list, we also
get the selected text and set it as the new window text for the combo.
This makes sure that the user sees the newly selected item and not the
previously selected item. (This is only necessary if the combo has the CBS_DROPDOWN
style,
as if it has CBS_DROPDOWNLIST
it will update immediately anyway.) That's it!
Originally from an electronics background, I moved into software in 1996, partly as a result of being made redundant, and partly because I was very much enjoying the small amount of coding (in-at-the-deep-end-C) that I had been doing!
I swiftly moved from C to C++, and learned MFC, and then went on to real-time C on Unix. After this I moved to the company for which I currently work, which specialises in Configuration Management software, and currently program mainly in C/C++, for Windows. I have been gradually moving their legacy C code over to use C++ (with STL, MFC, ATL, and WTL). I have pulled in other technologies (Java, C#, VB, COM, SOAP) where appropriate, especially when integrating with third-party products.
In addition to that, I have overseen the technical side of the company website (ASP, VBScript, JavaScript, HTML, CSS), and have also worked closely with colleagues working on other products (Web-based, C#, ASP.NET, SQL, etc).
For developing, I mainly use Visual Studio 2010, along with an in-house-designed editor based on Andrei Stcherbatchenko's
syntax parsing classes, and various (mostly freeware) tools. For website design, I use Dreaweaver CS3.
When not developing software, I enjoy listening to and playing music, playing electric and acoustic guitars and mandolin.