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的背景色改为所保存的背景色了。
本文来自CSDN博客,转载请标明出处:
阅读(2392) | 评论(0) | 转发(0) |