VC++MFC做文字編輯器(單文件模式)
2,在系統自動生成的CTextview_1Doc類裡面增加一個控制元件,用於文字文件的暫時存放:
class CTextview_1Doc : public CDocument
{
......
public:
CStringArray m_strContent;
}
然後在CTextview_1Doc類的Serialize函式裡面增加開啟、儲存文字檔案的程式:
void CTextview_1Doc::Serialize(CArchive& ar)
{
CString str;
if (ar.IsStoring())
{
// TODO: add storing code here
int nLines = (int)m_strContent.GetSize();
for ( int i=0; i<nLines; i++ )
{
str = m_strContent.GetAt( i );
ar.WriteString( str ); // 將字串集合類物件中文字儲存到硬碟
}
}
else
{
// TODO: add loading code here
while ( ar.ReadString( str ) )
{
m_strContent.Add( str ); // 將行文字新增到字串集合類物件中
}
}
}
然後滑鼠在CTextview_1Doc 上點選右鍵,在彈出選單裡面選擇:Add Virtual Function,在彈出的視窗中選中DeleteContents,點選“新增和編輯”按鈕。在生成的程式中新增以下程式碼:
void CTextview_1Doc::DeleteContents()
{
// TODO: Add your specialized code here and/or call the base class
m_strContent.RemoveAll(); // 清除集合類物件中的內容
CDocument::DeleteContents();
}
3,在系統自動生成的CTextview_1View類裡面增加一個編輯器的控制元件指標成員,用於在介面中生成文字編輯器:
class CTextview_1View : public CView
{
......
public:
CEdit* m_ctrlEdit;
}
該指標成員在類建立時要設定初始化值為NULL,否則執行起來就會出錯,如下:
CTextview_1View::CTextview_1View()
: m_ctrlEdit(NULL) //新增這一行初始化程式碼
{
// TODO: add construction code here
}
用第2點介紹的類似步驟,為CTextview_1View類重寫其OnInitialUpdate函式,新增內容如下:
void CTextview_1View::OnInitialUpdate()
{
CView::OnInitialUpdate();
// TODO: Add your specialized code here and/or call the base class
CRect rcClient;
GetClientRect( rcClient ); // 獲取當前檢視的客戶區大小
// if ( m_ctrlEdit ) delete m_ctrlEdit;
m_ctrlEdit = new CEdit();
m_ctrlEdit->Create( ES_MULTILINE | WS_CHILD | WS_VISIBLE
| WS_HSCROLL | ES_AUTOHSCROLL // 自動水平滾動
| WS_VSCROLL | ES_AUTOVSCROLL , // 自動垂直滾動
rcClient, this, 201); // 建立多行編輯控制元件
CTextview_1Doc* pDoc = GetDocument(); // 獲取與檢視相關聯的文件指標
// 以下是將文件中的m_strContent內容全部賦給str
CString str;
int nLines = (int)pDoc->m_strContent.GetSize();
for ( int i=0; i<nLines; i++ )
{
str = str + pDoc->m_strContent.GetAt( i );
str = str + "\r\n"; // 換行
}
m_ctrlEdit->SetTabStops( 16 ); // 設定Tab符大小
m_ctrlEdit->SetWindowText( str ); // 將文件內容傳給控制元件
}
4,現在執行一下,文字編輯器就做好了。
5,當然,現在的文字編輯器很不好用,因為不能滾動視窗。而且不會隨視窗的大小變化,因此需要增加一些程式碼。滑鼠停在CTextview_1View上點選右鍵,在彈出選單中選擇:Add Window Message Handle,在彈出的視窗中,選擇WM_SIZE訊息,並點選“Add & Edit”按鈕,在生成的函式中新增以下內容:
void CTextview_1View::OnSize(UINT nType, int cx, int cy)
{
CView::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
CRect rcClient;
GetClientRect( rcClient );
if ( m_ctrlEdit )
m_ctrlEdit->MoveWindow( rcClient ); // 改變編輯控制元件視窗大小
}
6,再執行,一個象模象樣的編輯器生成了。