MFC內ListBox並不會自動顯示水平捲軸,除非當你設定項目的長度超過ListBox的寬度,

因此下列做法是先記錄最大長度,超過最大長度再來設定水平捲軸

參考自:https://msdn.microsoft.com/zh-tw/library/1s0xed6b.aspx

    int max_length = 0;
    for ( int i = 0; i < m_vecFileList.size(); i++ ) {
        m_ListFileName.AddString(m_vecFileList[i].c_str());

        // 當超過最大長度時
        if ( m_vecFileList[i].length() > max_length ) {
            max_length = m_vecFileList[i].length();

            
            CString    str;
            CSize      sz;
            int      dx = 0;
            TEXTMETRIC tm;
            CDC*       pDC = m_ListFileName.GetDC();
            CFont*     pFont = m_ListFileName.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 k = 0; k < m_ListFileName.GetCount(); k++) // 這裡面加總該item所有字元長度
            {
                m_ListFileName.GetText(k, 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);
            m_ListFileName.ReleaseDC(pDC);

            // Set the horizontal extent so every character of all strings 
            // can be scrolled to.
            m_ListFileName.SetHorizontalExtent(dx);
            // should attention about listbox Hscrollbar length
        }
arrow
arrow

    跪著讀 發表在 痞客邦 留言(0) 人氣()