MFC自定义控件焦点设置求助:Dialog中按钮无法释放焦点
Hey there, let's tackle this focus issue you're seeing in your Dialog-based custom CWnd control. The fact that it works fine in SDI but breaks in Dialog gives us a clue—Dialogs have their own focus management logic that's a bit different from SDI's document/view setup. Here are some targeted fixes to try:
Handle
WM_KILLFOCUSproperly in your button controls
If your buttons are part of the CWnd-derived class (either custom or standard CButton), make sure you're overridingOnKillFocusto update their visual state. When a button loses focus, set a boolean flag (likem_bHasFocus = false) and callInvalidateRect()to trigger a repaint. In yourOnPaintmethod, check this flag to skip drawing the blue highlight when the button isn't focused.Ensure your Dialog uses the
WS_EX_CONTROLPARENTextended style
Dialogs depend on this style to manage smooth focus switching between child controls. You can enable it in two ways:- In the resource editor, go to your Dialog's properties → Extended Styles → check "Control Parent".
- Programmatically add it in
OnInitDialogwith:ModifyStyleEx(0, WS_EX_CONTROLPARENT);
Manually track and update focus in button click handlers
Add a member variable to your CWnd-derived class (e.g.,CButton* m_pCurrentFocusedBtn) to keep track of the button that's currently focused. When another button is clicked (handle theBN_CLICKEDmessage):- If
m_pCurrentFocusedBtnisn't null, send it aWM_KILLFOCUSmessage and set its focus state to false. - Call
pClickedBtn->SetFocus()to give focus to the new button, then updatem_pCurrentFocusedBtnto point to this new button.
- If
Don't block default focus handling in your CWnd class
If you've overriddenOnSetFocusorOnKillFocusin your CWnd-derived class, always make sure to call the base class implementation first. For example:void CMyCustomWnd::OnSetFocus(CWnd* pOldWnd) { CWnd::OnSetFocus(pOldWnd); // Let the base class handle standard focus logic // Your custom focus code here (if needed) }Skipping the base class call can disrupt the system's focus management, especially in Dialogs.
Give these steps a try—chances are one of them will resolve the stuck focus issue. The core problem here is that Dialogs have a more structured focus system compared to SDI, so you might need to explicitly handle transitions that happen automatically in the document/view framework.
内容的提问来源于stack exchange,提问作者심상원

