建立文档,写入与读取文件,CFile与Archive一起使用;
app是如何把文档、框架、视图组合起来的,以及IDR_MAINFRAME中7段各段意思
什么时候调用serialize:新建、装载、保存文档数据时框架调用。
代码:
\\写入文件
void CDocumentView::OnFileWrite()
{
// TODO: 在此添加命令处理程序代码
CFile file(_T("1.txt"),CFile::modeWrite |CFile::modeCreate);
CArchive ar(&file,CArchive::store);
int i=4;
wchar_t ch=_T('a');
float f=1.3;
CString str("rlj's lesson 13");
ar<<i<<ch<<f<<str;
}
\\读取文件
void CDocumentView::OnFileRead()
{
// TODO: 在此添加命令处理程序代码
/*CFile file(_T("1.txt"),CFile::modeRead);
CArchive ar(&file,CArchive::load);
int i;
char ch;
float f;
CString str,strResult;
ar>>i>>ch>>f>>str;
strResult.Format(_T("%d,%w,%f,%s"),i,ch,f,str);
MessageBox(strResult);*/
CFile file(_T("1.txt"),CFile::modeRead);
CArchive ar(&file,CArchive::load);
int i;
wchar_t ch;
float f;
CString str;
CString strResult;
ar>>i>>ch>>f>>str;
strResult.Format(_T("%d,%c,%f,%s"),i,ch,f,str);
MessageBox(strResult);
}
//点击点菜单
void CDocumentView::OnDot()
{
// TODO: 在此添加命令处理程序代码
m_nDrawType=1;
}
//点击直线菜单
void CDocumentView::OnLine()
{
// TODO: 在此添加命令处理程序代码
m_nDrawType=2;
}
//点击矩形菜单
void CDocumentView::OnRectangle()
{
// TODO: 在此添加命令处理程序代码
m_nDrawType=3;
}
//点击椭圆菜单
void CDocumentView::OnEclipse()
{
// TODO: 在此添加命令处理程序代码
m_nDrawType=4;
}
//鼠标左键按下时保存起点位置
void CDocumentView::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
m_ptOrigin=point;
CView::OnLButtonDown(nFlags, point);
}
//鼠标左键起来时画图并把图形保存进m_obArray中
void CDocumentView::OnLButtonUp(UINT nFlags, CPoint point)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
CClientDC dc(this);
CPen pen(PS_SOLID,1,RGB(255,0,0));
dc.SelectObject(&pen);
CBrush *pBrush=CBrush::FromHandle((HBRUSH)GetStockObject(NULL_BRUSH));
dc.SelectObject(pBrush);
switch(m_nDrawType)
{
case 1:
dc.SetPixel(point,RGB(255,0,0));
break;
case 2:
dc.MoveTo(m_ptOrigin);
dc.LineTo(point);
break;
case 3:
dc.Rectangle(CRect(m_ptOrigin,point));
break;
case 4:
dc.Ellipse(CRect(m_ptOrigin,point));
break;
}
CGraph *pGraph = new CGraph(m_nDrawType,m_ptOrigin,point);
//m_obArray.Add(pGraph);
CDocumentDoc *pDoc=GetDocument();
pDoc->m_obArray.Add(pGraph);
CView::OnLButtonUp(nFlags, point);
}
//新建窗口或重画窗口时显示所画内容
void CDocumentView::OnDraw(CDC* pDC)
{
CDocumentDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: 在此处为本机数据添加绘制代码
int nCount;
//nCount=m_obArray.GetSize();
nCount=pDoc->m_obArray.GetSize();
for(int i=0;i<nCount;i++)
{
//((CGraph*) m_obArray.GetAt(i))->Draw(pDC);
((CGraph*)pDoc->m_obArray.GetAt(i))->Draw(pDC);
}
}
//在删除文档时由框架调用,删除文档中内容
void CDocumentDoc::DeleteContents()
{
// TODO: 在此添加专用代码和/或调用基类
int nCount;
nCount=m_obArray.GetSize();
for(int i=0;i<nCount;i++)
{
delete m_obArray.GetAt(i);
}
m_obArray.RemoveAll();
/*while(nCount--
{
delete m_obArray.GetAt(nCount);
m_obArray.RemoveAt(nCount);
}*/
CDocument::DeleteContents();
}