I want to know when the user has clicked in a CListBox, but outside of any item. I was hoping to get some notification in the containing dialog so I can process the point to determine if it is inside an item via mylistbox.ItemFromPoint(flags,outside)
. But clicks within the listbox don't seem to result in such events. What event should I be looking for in the parent dialog, and what needs to be set up to enable it? I really don't care if it is a click or just mousedown.
My purpose for this is to deselect all items if the user clicks outside of any item, with mylistbox.SetCurSel(-1)
.
Addendum: This is the full code for the class implemented as suggested by @mercurydime.
(Header)
#ifndef INCLUDE_CMYLISTBOX_H
#define INCLUDE_CMYLISTBOX_H
class CMyListBox : public CListBox
{
public:
CMyListBox();
void allow_deselect( bool allow = true );
protected:
bool m_allow_deselect;
afx_msg void OnLButtonDown( UINT flags, CPoint point );
DECLARE_MESSAGE_MAP()
};
#endif // INCLUDE_CMYLISTBOX_H
(Body)
#include "stdafx.h"
#include "CMyListBox.h"
CMyListBox::CMyListBox()
: CListBox(), m_allow_deselect( false )
{
}
void CMyListBox::allow_deselect( bool allow )
{
m_allow_deselect = allow;
}
BEGIN_MESSAGE_MAP( CMyListBox, CListBox )
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
void CMyListBox::OnLButtonDown( UINT flags, CPoint point )
{
if( m_allow_deselect )
{
BOOL outside( TRUE );
ItemFromPoint( point, outside );
if( outside )
SetCurSel( -1 );
}
CListBox::OnLButtonDown( flags, point );
}
CListBox
:Ctrl+Shift+X
Click the down arrow on the Add Class button
Select the MFC Class menu item
Make sure the base class is set to CListBox
WM_LBUTTONDOWN
Ctrl+Shift+X
Click the Messages tab
Double-click WM_LBUTTONDOWN
ItemFromPoint
code inside the handlervoid CMyListBox::OnLButtonDown(UINT nFlags, CPoint point)
{
BOOL bOutside = TRUE;
UINT uItem = ItemFromPoint(point, bOutside);
if (bOutside)
{
// do whatever
}
CListBox::OnLButtonDown(nFlags, point);
}