1. 程式人生 > >CComboBox增加水平滾動條

CComboBox增加水平滾動條

1. 新增WS_HSCROLL樣式

使用記事本開啟.rc資原始檔增加WS_HSCROLL樣式(VS的資源編輯視窗中無法新增),如下圖所示。
新增WS_HSCROLL樣式

2.新增如下程式碼

void CXXXDlg::AddHScroll(UINT idComboBox)
{
    CComboBox *pCB = (CComboBox*)GetDlgItem(idComboBox);
    if (nullptr == pCB) return;

    CComboBox &Cmb = *pCB;
    // Find the longest string in the combo box.
CString str; CSize sz; int dx = 0; TEXTMETRIC tm = { 0 }; CDC* pDC = Cmb.GetDC(); CFont* pFont = Cmb.GetFont(); // Select the listbox font, save the old font CFont* pOldFont = pDC->SelectObject(pFont); // Get the text metrics for avg char width pDC->GetTextMetrics
(&tm); for (int i = 0; i < Cmb.GetCount(); i++) { Cmb.GetLBText(i, str); sz = pDC->GetTextExtent(str); // Add the avg width to prevent clipping sz.cx += tm.tmAveCharWidth; if (sz.cx > dx) dx = sz.cx; } // Select the old font back into the DC
pDC->SelectObject(pOldFont); Cmb.ReleaseDC(pDC); // Set the horizontal extent so every character of all strings can // be scrolled to. Cmb.SetHorizontalExtent(dx); }

3.在OnInitDialog中呼叫函式設定水平滾動資訊

BOOL CXXXDlg::OnInitDialog()
{
	//---
	AddHScroll(IDC_COMBO_L_LL_CMD);
	//---
}

參考文章:http://ntcoder.com/bab/2009/05/28/add-horizontal-scrollbar-to-a-combo-box/