动态地重新创建一个组合框

介绍 我经常发现自己需要做的是切换组合框 或从排序。这是一个原因(虽然不是 主要原因)我想出了我的动态 可切换的控制。但是,在创作后改变这些风格是有意义的 那个组合盒不支持。这里提供的这个函数将重新创建这个组合 框,使样式更改生效。该函数将保留所有列表项 项数据和当前选择或输入的文本。 例如,当在combobox上修改样式以包括或删除CBS_SORT时, 可以看到(通过使用GetStyle()或使用像spy++这样的工具)控制 确实有新的样式,但控件的行为没有改变。 这里的函数只是从控件获取当前信息,比如样式,字体等等, 并使用这些值重

  

 

新创建控件。 如何使用 我最初有一个ccombobox派生类,其中一个成员函数 重新创建控制,但认为这是比它的价值更多的麻烦 我的大部分组合来自于其他东西。因此,我把它作为一个整体来呈现 函数,它应该包含在全局库文件中,以便您可以调用它 在任何时间在任何组合盒上。 为了改变一个组合的风格,你应该执行通常的方法 树立新风格。 隐藏,复制Code

combo.ModifyStyle(0, CBS_SORT);

在电话之后,你应该打电话给: 隐藏,复制Code

RecreateComboBox(&combo)

该函数接受一个可选的空指针lpParam,它被传递给 CreateEx上 重新创建控制。如果在创建控件时有特殊要求, 通常为创建参数传递一些数据,然后应该传递 这里也一样。大多数开发人员可以简单地忽略这个参数。 这个函数 重新创建这个组合的函数如下: 隐藏,收缩,复制Code

// recreate the combo box by copying styles etc, and list items
// and applying them to a newly created control
BOOL RecreateComboBox(CComboBox* pCombo, LPVOID lpParam/*=0*/)
{
	if (pCombo == NULL)
		return FALSE;
	if (pCombo->GetSafeHwnd() == NULL)
		return FALSE;

	CWnd* pParent = pCombo->GetParent();
	if (pParent == NULL)
		return FALSE;

	// get current attributes
	DWORD dwStyle = pCombo->GetStyle();
	DWORD dwStyleEx = pCombo->GetExStyle();
	CRect rc;
	pCombo->GetDroppedControlRect(&rc);
	pParent->ScreenToClient(&rc);	// map to client co-ords
	UINT nID = pCombo->GetDlgCtrlID();
	CFont* pFont = pCombo->GetFont();
	CWnd* pWndAfter = pCombo->GetNextWindow(GW_HWNDPREV);

	// get the currently selected text (and whether it is a valid list selection)
	CString sCurText;
	int nCurSel = pCombo->GetCurSel();
	BOOL bItemSelValid = nCurSel != -1;
	if (bItemSelValid)
		pCombo->GetLBText(nCurSel, sCurText);
	else
		pCombo->GetWindowText(sCurText);

	// copy the combo box items into a temp combobox (not sorted)
	// along with each item's data
	CComboBox comboNew;
	if (! comboNew.CreateEx(dwStyleEx, _T("COMBOBOX"), _T(""), 
                                 dwStyle, rc, pParent, nID, lpParam))
	  return FALSE;
	comboNew.SetFont(pFont);
	int nNumItems = pCombo->GetCount();
	for (int n = 0; n < nNumItems; n++)
	{
		CString sText;
		pCombo->GetLBText(n, sText);
		int nNewIndex = comboNew.AddString(sText);
		comboNew.SetItemData(nNewIndex, pCombo->GetItemData(n));
	}
	// re-set selected text
	if (bItemSelValid)
		comboNew.SetCurSel(comboNew.FindStringExact(-1, sCurText));
	else
		comboNew.SetWindowText(sCurText);

	// destroy the existing window, then attach the new one
	pCombo->DestroyWindow();
	HWND hwnd = comboNew.Detach();
	pCombo->Attach(hwnd);

	// position correctly in z-order
	pCombo->SetWindowPos(pWndAfter == NULL ? 
                                &CWnd::wndBottom : 
                               pWndAfter, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);

	return TRUE;
}

另请参阅 动态地重新创建一个列表框 : 函数在运行时重新创建一个列表框,以允许使用新样式、保留其数据和选择 动态切换的多用途控制 : 允许在运行时在许多控制类型之间切换的控件, 例如:组合,编辑等 历史 版本1 - 2002年7月26日-第一版版本2 - 2002年7月30日-修改包括Jean-Michel LE FOL和Davide Zaccanti建议的修改 本文转载于:http://www.diyabc.com/frontweb/news334.html

posted @ 2020-08-05 08:52  Dincat  阅读(196)  评论(0编辑  收藏  举报