Rich Edit 控件:IDC_EDIT 变量:m_edit
四个按钮:颜色、字体、保存、打开
IDC_BTN_COLOR, IDC_BTN_FONT, IDC_BTN_SAVE, IDC_BTN_LOAD
四个按钮的响应函数:
void CRichEditDemoDlg::OnBnClickedBtnColor()
{
// TODO: 在此添加控件通知处理程序代码
//定义并初始化文字格式结构
CHARFORMAT cf={0};
cf.cbSize=sizeof(cf);
//取得文本框当前文字的格式
m_edit.GetSelectionCharFormat(cf);
//创建颜色对话框,并用取得的文字格式初始化对话框
CColorDialog dlg(cf.crTextColor,CC_FULLOPEN,this);
//显示对话框,选择颜色
if(dlg.DoModal()==IDOK)
{
//取得用户所选颜色
cf.crTextColor=dlg.GetColor();
//将文本格式ixnxi设置到文本框当前文本
cf.dwMask=CFM_COLOR;
cf.dwEffects=0;
m_edit.SetSelectionCharFormat(cf);
}
}
void CRichEditDemoDlg::OnBnClickedBtnFont()
{
// TODO: 在此添加控件通知处理程序代码
CHARFORMAT cf={0};
cf.cbSize=sizeof(cf);
m_edit.GetSelectionCharFormat(cf);
CFontDialog dlg(cf);
if(dlg.DoModal()==IDOK)
{
dlg.GetCharFormat(cf);
cf.dwMask&=~CFM_COLOR;
m_edit.SetSelectionCharFormat(cf);
}
}
void CRichEditDemoDlg::OnBnClickedBtnSave()
{
// TODO: 在此添加控件通知处理程序代码
CFileDialog dlg(FALSE,_T("rtf"),NULL,
OFN_PATHMUSTEXIST|OFN_OVERWRITEPROMPT|OFN_HIDEREADONLY,
_T("*.rtf|*.rtf|*.*|*.*||"),this);
if(dlg.DoModal()!=IDOK)
return;
CString strFile=dlg.GetPathName();
CFile file;
if(!file.Open(strFile,CFile::modeCreate|CFile::modeWrite))
{
AfxMessageBox(_T("WRONG"));
return;
}
EDITSTREAM es={0};
es.dwCookie=(DWORD)&file;
es.pfnCallback=StreamOutProc;
int nFormat;
if(_tcsicmp(dlg.GetFileExt(),_T("rtf"))==0)
nFormat=SF_RTF;
else
nFormat=SF_TEXT;
m_edit.StreamOut(nFormat,es);
file.Close();
}
void CRichEditDemoDlg::OnBnClickedBtnLoad()
{
// TODO: 在此添加控件通知处理程序代码
CFileDialog dlg(TRUE,NULL,NULL,
OFN_FILEMUSTEXIST,_T("*.rtf|*.rtf|*.*|*.*||"),this);
if(dlg.DoModal()!=IDOK)
return;
CString strFile=dlg.GetPathName();
CFile file;
if(!file.Open(strFile,CFile::modeRead))
{
AfxMessageBox(_T("WRONG"));
return;
}
m_edit.SetWindowTextW(_T(""));
EDITSTREAM es={0};
es.dwCookie=(DWORD)&file;
es.pfnCallback=StreamInProc;
int nFormat;
if(_tcsicmp(dlg.GetFileExt(),_T("rtf"))==0)
nFormat=SF_RTF;
else
nFormat=SF_TEXT;
m_edit.StreamIn(nFormat,es);
file.Close();
}
为主对话框添加两个静态函数作为Rich Edit控件的输入、输出数据回调函数,声明:
protected:
static DWORD CALLBACK StreamOutProc(
DWORD dwCookie,LPBYTE pbBuff,LONG cb,LONG *pcb);
static DWORD CALLBACK StreamInProc(
DWORD dwCookie,LPBYTE pbBuff,LONG cb,LONG *pcb);
定义:
DWORD CALLBACK CRichEditDemoDlg::StreamOutProc(
DWORD dwCookie,LPBYTE pbBuff,LONG cb,LONG *pcb)
{
CFile *pFile=(CFile*)dwCookie;
*pcb=pFile->Read(pbBuff,cb);
return 0;
}
DWORD CALLBACK CRichEditDemoDlg::StreamInProc(
DWORD dwCookie,LPBYTE pbBuff,LONG cb,LONG *pcb)
{
CFile *pFile=(CFile*)dwCookie;
pFile->Read(pbBuff,cb);
*pcb=cb;
return 0;
}
在BOOL CRichEditDemoApp::InitInstance()中添加初始化代码:
AfxInitRichEdit2();