动态地重新创建一个列表框

介绍 这篇文章是我那篇文章的配套文章 动态 重新创建一个组合框。与组合框类似,我经常发现自己 需要切换列表框到或从排序,或到或从多选择。作为 使用组合框,在创建后更改这些样式是一个列表框 不支持。这里提供的函数将重新创建列表框,以便 样式更改生效。该函数将保留所有列表项,包括item 数据和当前选中的项。 例如,当在listbox上修改样式以包括或删除LBS_SORT时, 可以看到(通过使用GetStyle()或使用像spy++这样的工具)控制 确实有新的样式,但控件的行为没有改变。 这里的函数只是从控件获取当前信息,比如样式,字体等等, 并使

  

 

用这些值重新创建控件。 如何使用 我最初有一个clistbox派生类,其中一个成员函数 重新创建控制,但认为这是比它的价值更多的麻烦 我通常使用来自其他基地的控制。因此,我把它作为一个整体来呈现 函数,它应该包含在全局库文件中,以便您可以调用它 在任何时间在任何列表框。 要更改列表框的样式,应该执行通常的方法 树立新风格。 隐藏,复制Code

list.ModifyStyle(0, LBS_SORT);

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

RecreateListBox(&list)

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

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

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

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

	// create the new list box and copy the old list box items 
	// into a new listbox along with each item's data, and selection state
	CListBox listNew;
	if (! listNew.CreateEx(dwStyleEx, _T("LISTBOX"), _T(""), dwStyle, 
                                rc, pParent, nID, lpParam))
	  return FALSE;
	listNew.SetFont(pFont);
	int nNumItems = pList->GetCount();
	BOOL bMultiSel = (dwStyle & LBS_MULTIPLESEL || dwStyle & LBS_EXTENDEDSEL);
	for (int n = 0; n < nNumItems; n++)
	{
		CString sText;
		pList->GetText(n, sText);
		int nNewIndex = listNew.AddString(sText);
		listNew.SetItemData(nNewIndex, pList->GetItemData(n));
		if (bMultiSel && pList->GetSel(n))
			listNew.SetSel(nNewIndex);
	}
	if (! bMultiSel)
	{
		int nCurSel = pList->GetCurSel();
		if (nCurSel != -1)
		{
			CString sSelText;
			// get the selection in the old list
			pList->GetText(nCurSel, sSelText);
			// now find and select it in the new list
			listNew.SetCurSel(listNew.FindStringExact(-1, sSelText));
		}
	}
	// destroy the existing window, then attach the new one
	pList->DestroyWindow();
	HWND hwnd = listNew.Detach();
	pList->Attach(hwnd);

	// position correctly in z-order
	pList->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/news238.html

posted @ 2020-08-04 09:15  Dincat  阅读(177)  评论(0编辑  收藏  举报