VC代码设置CComboBox下拉列表项条数

这个问题困扰了很长时间,没有找到很好的解决方案;

方式1:在IDE界面上手动调整,这个很简单,问题是如果代码动态创建的CComboBox则无法用这个方法解决;

方式2:MoveWindow

方式3:SetWindowPos

方式2、3可以实现上面的需求,只是没有办法准确控制显示的条数。终于在网上发现了http://hi.baidu.com/netspirit/blog/item/c033012cbb44a9e48b1399e0.html,同样,这里记录下来,以免忘记。

void set_DropDownSize(CComboBox& box, UINT LinesToDisplay) 
/*-------------------------------------------------------------------------- 
* Purpose: Set the proper number of lines in a drop-down list or 
* combo box. 
* Description: Resizes the combo box window to fit the proper number 
* of lines. The window must exist before calling this function. 
* This function should be called when the combo box is created, and when 
* the font of the combo box changes. (e.g. WM_SETTINGCHANGE) 
* Testing needed: 
* Are there cases where SM_CYBORDER should be used instead of SM_CYEDGE? 
* owner-draw variable height combo box 
* Subclassed combo box with horizontal scroll-bar 
* Returns: nothing 
* Author: KTM 
*--------------------------------------------------------------------------*/ 

ASSERT(IsWindow(box)); // Window must exist or SetWindowPos won't work 

CRect cbSize; // current size of combo box 
int Height; // new height for drop-down portion of combo box 

box.GetClientRect(cbSize); 
Height = box.GetItemHeight(-1); // start with size of the edit-box portion 
Height += box.GetItemHeight(0) * LinesToDisplay; // add height of lines of text 

// Note: The use of SM_CYEDGE assumes that we're using Windows '95 
// Now add on the height of the border of the edit box 
Height += GetSystemMetrics(SM_CYEDGE) * 2; // top & bottom edges 

// The height of the border of the drop-down box 
Height += GetSystemMetrics(SM_CYEDGE) * 2; // top & bottom edges 

// now set the size of the window 
box.SetWindowPos(NULL, // not relative to any other windows 
0, 0, // TopLeft corner doesn't change 
cbSize.right, Height, // existing width, new height 
SWP_NOMOVE | SWP_NOZORDER // don't move box or change z-ordering. 
); 
}


需要注意的有两点:

1、等填充完CComboBox后在调用上面的方法

2、CComboBox调用Create时,记得带上WS_VSCROLL样式,否则显示的条数只有设定的几条。当然这个问题并不是调用上面的方法引起的;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章