①新建一个MFC AppWizard(exe)工程,选择单文档,最后一步选择"C[你的工程名]View"类,选择其基类(Base class):CRichEditView。这样就能建立一个可以编辑文本的自定义工作区的工程了。
②选择Resource中的Toolbar来新建工具条项,随便画一个图形,编辑其ID为ID_SEARCH,按Ctrl+W(或者点击View-ClassWizard)来启动消息映射,Object IDs中ID_SEARCH身上发生了COMMOND点击事件,应该由CMainFrame类中的OnSearch() 函数来处理。
③回到Resource视图中,右键Dialog选择Insert Dialog,
④ID为IDD_SEARCH_DIALOG,里面添加编辑框IDC_WORD,按钮IDC_SEARCH并且映射函数CDlgSearch::OnSearch() ,按钮IDCANCEL,然后双击对话框new一个class:CDlgSearch
⑤在②中的CMainFrame::OnSearch() 函数中显示刚才的非模式对话框:
#include "DlgSearch.h" void CMainFrame::OnSearch() { // TODO: Add your command handler code here CDlgSearch *pDlg = new CDlgSearch(this);//实例化窗口 pDlg->Create(IDD_SEARCH_DIALOG,this);//创建非模式窗口 pDlg->CenterWindow(this);//居中显示 pDlg->ShowWindow(SW_SHOW);//显示窗口 }⑥在CDlgSearch类中映射CDlgSearch::OnShowWindow(BOOL bShow, UINT nStatus) ,编辑:
#include "MainFrm.h" #include "TestView.h" void CDlgSearch::OnShowWindow(BOOL bShow, UINT nStatus) { CDialog::OnShowWindow(bShow, nStatus); // TODO: Add your message handler code here CEdit *pEdit = (CEdit *)GetDlgItem(IDC_WORD);//获取编辑框控件 pEdit->SetFocus();//编辑框获取焦点 //获取工作区视图 CMainFrame *pFrame = (CMainFrame *)AfxGetMainWnd(); CTestView *pView = (CTestView *)pFrame->GetActiveView(); CRichEditCtrl *pCtrl = &(pView->GetRichEditCtrl()); this->SetDlgItemText(IDC_WORD,pCtrl->GetSelText()); pEdit->SetSel(0,-1); }
void CDlgSearch::OnSearch() { // TODO: Add your command handler code here CString word = "b"; //GetDlgItemText(IDC_WORD,word); CMainFrame *pFrame = (CMainFrame *)AfxGetMainWnd(); CTestView *pView = (CTestView *)pFrame->GetActiveView(); CRichEditCtrl *pCtrl = &(pView->GetRichEditCtrl()); FINDTEXTEX ft; ft.chrg.cpMin = 0; ft.chrg.cpMax = -1; ft.lpstrText = (LPSTR) word.GetBuffer(1000); long n = pCtrl->FindText(FR_MATCHCASE|FR_WHOLEWORD,&ft); if (n != -1) pCtrl->SetSel(ft.chrg.cpMin,ft.chrg.cpMax); }好了,到这里大功告成了,运行一下,调试试试吧。