CComboBox改变风格

    技术2025-11-28  6

    做项目的过程中,遇到个问题,需要根据类型改变CComboBox控件的风格,自己做了个,感觉不完善,后来在codeproject上找到了个解决得比较好的(http://www.codeproject.com/KB/combobox/recreatecombobox.aspx),记录如下:

    BOOL RecreateComboBox(CComboBox* pCombo, LPVOID lpParam/*=0*/) { if (pCombo == NULL) return FALSE; if (pCombo->GetSafeHwnd() == NULL) return FALSE; CWnd* pParent = pCombo->GetParent(); if (pParent == NULL) return FALSE; // get current attributes DWORD dwStyle = pCombo->GetStyle(); DWORD dwStyleEx = pCombo->GetExStyle(); CRect rc; pCombo->GetDroppedControlRect(&rc); pParent->ScreenToClient(&rc); // map to client co-ords UINT nID = pCombo->GetDlgCtrlID(); CFont* pFont = pCombo->GetFont(); CWnd* pWndAfter = pCombo->GetNextWindow(GW_HWNDPREV); // get the currently selected text (and whether it is a valid list selection) CString sCurText; int nCurSel = pCombo->GetCurSel(); BOOL bItemSelValid = nCurSel != -1; if (bItemSelValid) pCombo->GetLBText(nCurSel, sCurText); else pCombo->GetWindowText(sCurText); // copy the combo box items into a temp combobox (not sorted) // along with each item's data CComboBox comboNew; if (! comboNew.CreateEx(dwStyleEx, _T("COMBOBOX"), _T(""), dwStyle, rc, pParent, nID, lpParam)) return FALSE; comboNew.SetFont(pFont); int nNumItems = pCombo->GetCount(); for (int n = 0; n < nNumItems; n++) { CString sText; pCombo->GetLBText(n, sText); int nNewIndex = comboNew.AddString(sText); comboNew.SetItemData(nNewIndex, pCombo->GetItemData(n)); } // re-set selected text if (bItemSelValid) comboNew.SetCurSel(comboNew.FindStringExact(-1, sCurText)); else comboNew.SetWindowText(sCurText); // destroy the existing window, then attach the new one pCombo->DestroyWindow(); HWND hwnd = comboNew.Detach(); pCombo->Attach(hwnd); // position correctly in z-order pCombo->SetWindowPos(pWndAfter == NULL ? &CWnd::wndBottom : pWndAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); return TRUE; }

     

    使用方法:m_combo.ModifyStyle(CBS_DROPDOWNLIST,CBS_DROPDOWN);

                   RecreateComboBox(&m_combo);

    最新回复(0)