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樣式,否則顯示的條數只有設定的幾條。當然這個問題並不是調用上面的方法引起的;

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