http://www.codeguru.com/cpp/com-tech/activex/controls/article.php/c5519/
Persist ActiveX Controls At Runtime
乍一看這標題,嚇我一跳,運行時持久化控制項,這怎麼可能,等看過內容,發現原來是只有CArchive參數的程式碼片段,估計是要用自己的檔案來持久化的,純粹誤導嘛;不過這段內容本身還是蠻有意思的,因此用了一個例子把它給弄完整了。
1.建立一對話方塊工程tdlghello,插入ActiveX控制項(就Microsoft ListView吧),產生一堆檔案,按下不表。在對對話方塊模板上拉進一控制項,關聯變數CListView1 m_lv;
2.添加三按鈕(裝載,儲存和設定背景色),添加代碼如下:
void CTdlghelloDlg::OnButtonColor()
{
// TODO: Add your control notification handler code here
CColorDialog dlg(m_lv.GetBackColor());
if(dlg.DoModal() == IDOK){
m_lv.SetBackColor(dlg.GetColor());
}
}
void CTdlghelloDlg::OnButtonSave()
{
// TODO: Add your control notification handler code here
CString str = _T("mypersist.dat");
CFile file;
if(file.Open(str, CFile::typeBinary | CFile::modeWrite | CFile::modeCreate)){
CArchive ar(&file, CArchive::store);
PersistActiveX(ar, &m_lv);
ar.Close();
file.Close();
}
}
void CTdlghelloDlg::OnButtonLoad()
{
// TODO: Add your control notification handler code here
CString str = _T("mypersist.dat");
CFile file;
if(file.Open(str, CFile::typeBinary | CFile::modeRead)){
CArchive ar(&file, CArchive::load);
PersistActiveX(ar, &m_lv);
ar.Close();
file.Close();
}
}
mypersist.dat就是用來儲存控制項屬性的檔案
3.上面的PersistActiveX就是原文中的函數段,簡單的添加這個函數,把函數內代碼拷過來就是。
BOOL CTdlghelloDlg::PersistActiveX(CArchive &ar, CWnd *pActiveX)
{
ASSERT(pActiveX);
HRESULT hr = E_FAIL;
// Create an archive stream
CArchiveStream stm(&ar);
LPPERSISTSTREAMINIT pPersStm = NULL;
LPUNKNOWN lpUnk = pActiveX->GetControlUnknown();
if(lpUnk)
{
// We have the IUnknown interface, so
// get the IPersistStreamInit
lpUnk->QueryInterface(IID_IPersistStreamInit,
(LPVOID*)&pPersStm);
if(pPersStm)
{
// We have the relevant interface so load or save the data
// based on the type of archive we have.
if(ar.IsLoading())
{
hr = pPersStm->Load(&stm);
}
else
{
hr = pPersStm->Save(&stm, FALSE);
}
}
// Must release the interface
pPersStm->Release();
}
return SUCCEEDED(hr);
}
這裡的CArchiveStream需要#include "afxpriv2.h"
4.編譯,運行,點按鈕設定背景色,設定一背景色,然後點儲存按鈕。退出程式,運行,點裝載,可以發現確實將ListView的背景色改為所儲存的背景色了。