将几个数字格式化之后插入一个listbox,要求字符要右对齐,我使用了sprintf函数,但是对得还是不齐,代码大致如下: for(i=m_GraySelVec.size()-1;i>-1;i--)
 {
              char szSel[256];
  memset(szSel,'\0',256);
sprintf(szSel,"%5d--%5d:%8d%8d%8d",m_GraySelVec[i].Min,m_GraySelVec[i].Max,GetRValue(m_pPallette[m_ColorIndexVec[i]]),GetGValue(m_pPallette[m_ColorIndexVec[i]]),GetBValue(m_pPallette[m_ColorIndexVec[i]]));  pListBoxPct->InsertString(-1,szSel);
 }效果图如下,图中上面的就是listbox,可以看到第一行和其它行对不齐:     大家有没有更好的字符串对齐的办法呢?   我的编译环境是:VS2005 sp1, Win XP sp2.

解决方案 »

  1.   

    貌似不行把。为什么不用listctrl呢
      

  2.   

    设置等宽字体,比如Courier New。
      

  3.   


        listbox设置为等宽字体的代码:   CFont font;
    LOGFONT lf;
    memset(&lf, 0, sizeof(LOGFONT));   // Clear out structure.
    lf.lfHeight = 15;  // Request a 15-pixel-high font
            lf.lfWidth = 1;
    strcpy(lf.lfFaceName, "Courier New");    //    with face name "Courier New".
    font.CreateFontIndirect(&lf);    // Create the font.        pListBoxPct->SetFont(&font); for(i=m_GraySelVec.size()-1;i>-1;i--)
     {
                  char szSel[256];
         memset(szSel,'\0',256);
        sprintf(szSel,"%5d-%5d:%5d%5d%5d",m_GraySelVec[i].Min,m_GraySelVec[i].Max,GetRValue(m_pPallette[m_ColorIndexVec[i]]),GetGValue(m_pPallette[m_ColorIndexVec[i]]),GetBValue(m_pPallette[m_ColorIndexVec[i]]));  pListBoxPct->InsertString(-1,szSel);
     }
         
         listbox设置为等宽字体后的字符对齐效果图:       感觉第一行和其它行还是对不齐,不知道为何?
      

  4.   


        设置listbox的Right Align Text属性为TRUE并不符合我的要求,因为这只是所有的字符串靠右对齐。我要求的效果是
    字符串放在靠左的部分,然后逐个部分对齐。比如731--1184:  0  125  125 和 1195--1458:  15 255 180
    我要求731--1184:和1195--1458:右对齐,0和15右对齐,125和255右对齐,125和180右对齐。
      

  5.   


    在对话框类设置一个私有变量:CFont *m_pFont;在OnInitDialog()函数里:CListBox *pListBoxPct = static_cast<CListBox*>(GetDlgItem(IDC_LISTPCTLOOKUP));
    if(NULL==pListBoxPct)
    return FALSE; m_pFont = new CFont();//
    LOGFONT lf;
    memset(&lf, 0, sizeof(LOGFONT));   // Clear out structure.
    lf.lfHeight = 15;  // Request a 15-pixel-high font
    lf.lfWidth = 1;
    strcpy(lf.lfFaceName, "Courier New");    //    with face name "Arial".
    m_pFont->CreateFontIndirect(&lf);    // Create the font.
    pListBoxPct->SetFont(m_pFont);在对话框类的析构函数里: if (NULL!=m_pFont)   
        m_pFont->DeleteObject();
        效果图如下:     数字不能正常显示,我怀疑是不是我采用多字节方式编译的缘故,但是我又不能采用unicode方式编译(因为使用了第三方库,不能用unicode)。
      

  6.   


        
        用Fixedsys字体之后的效果图:
        感觉第一行和其它行还是对不齐,不知道为何? 
      

  7.   

    lf.lfWidth = 1;
    ???