Ownerdraw ComboBox文本垂直居中对齐

时间:2020-02-03 06:56:37

标签: mfc

我正在基于MFC对话框的应用程序中使用所有者绘图ComboBox。

我可以绘制Combobox的ListBox项,但是无法在ComboBox的编辑控件中设置垂直居中对齐的ComboBox文本,它始终呈现在编辑控件的左上方。

我需要在编辑控件中将文本呈现在垂直中心。

如何实现? CombobOx样式:-CBS_DROPDOWN | CBS_OWNERDRAWFIXED | CBS_SORT | CBS_HASSTRINGS | CBS_UPPERCASE | WS_VSCROLL | WS_TABSTOP

BOOL CTestComboDlg::OnInitDialog()
{
    CDialog::OnInitDialog();

    // TODO: Add extra initialization here
    COMBOBOXINFO cbi = { sizeof cbi};
    m_ctrlCombo.GetComboBoxInfo(&cbi);
    CRect r;
    CWnd* p = CWnd::FromHandle(cbi.hwndItem);
    ((CEdit*)p)->GetRect(&r);

    r.DeflateRect(10,10);
    ((CEdit*)p)->SetRect(r);
    m_ctrlCombo.AddString("GHKL");
    m_ctrlCombo.AddString("FGHJKL");
    m_ctrlCombo.AddString("ASDFGH");
    m_ctrlCombo.AddString("QWERTY");
    m_ctrlCombo.SetCurSel(0);
    return TRUE;  // return TRUE  unless you set the focus to a control
}

void CMyComboBox::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
    CDC dc;
    dc.Attach(lpDrawItemStruct->hDC);

    LPCTSTR lpszText = (LPCTSTR) lpDrawItemStruct->itemData;
    ASSERT(lpszText != NULL);

    if (lpDrawItemStruct->itemID != -1)
        dc.DrawText(lpszText, strlen(lpszText),
        &lpDrawItemStruct->rcItem,
        DT_LEFT|DT_SINGLELINE|DT_VCENTER);
    dc.Detach();

}

谢谢

1 个答案:

答案 0 :(得分:0)

所有者绘制的组合框控件的显示高度将高于在对话框资源中设置的高度:资源编辑器中组合框的默认高度为12像素,但是在运行的应用程序中,其显示高度将高2像素。 因此,我使用下面的代码来调整组合框的编辑控件的高度,并使文本垂直居中对齐

TEXTMETRIC tm;
HDC hDC = ::GetDC(NULL);
CFont* pFont = GetFont();
HFONT hFontOld = (HFONT)SelectObject(hDC, pFont->GetSafeHandle());
GetTextMetrics(hDC, &tm);
SetItemHeight(-1,tm.tmHeight + tm.tmExternalLeading + 1);
SelectObject(hDC, hFontOld);
::ReleaseDC(NULL, hDC);