VC++查找替换对话框
[cpp]
int curpos;
int pos;
CFindReplaceDialog *pFindReplaceDlg;
(2)为了使父窗口知道查找/替换请求,必须使用RegisterWindowMessage函数,它的返回值是应用实例唯一的消息号。
[cpp]
static UINT WM_FINDMESSAGE = ::RegisterWindowMessage(FINDMSGSTRING);
A Find or Replace dialog box sends the FINDMSGSTRING registered message to the window procedure of its owner window when the user clicks the Find Next, Replace, or Replace All button, or closes the dialog box.
(3)在源文件里面将消息映射函数与WM_FINDMESSAGE消息关联
[cpp]
BEGIN_MESSAGE_MAP(CDialogTestDlg, CDialog)
//{{AFX_MSG_MAP(CDialogTestDlg)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_REGISTERED_MESSAGE(WM_FINDMESSAGE,OnFindReplace)
ON_BN_CLICKED(IDC_CHECK, OnCheck)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
(4)添加消息响应函数OnFindReplace
[cpp]
long CDialogTestDlg::OnFindReplace(WPARAM wParam, LPARAM lParam)
{
//判断是否关闭查找替换对话框
if(pFindReplaceDlg->IsTerminating())
{
pFindReplaceDlg = NULL;
return 0;
}
//获取需要查找的文本
CString strFind = pFindReplaceDlg->GetFindString();
int lenStrFind = strFind.GetLength();
//获取需要替换所查找的文本的文本
CString strReplace = pFindReplaceDlg->GetReplaceString();
int lenStrReplace = strReplace.GetLength();
CString strPos,strEdit;
//"Find Next"
if(pFindReplaceDlg->FindNext())
{
m_ctrlEdit.GetWindowText(strEdit);
pos = strEdit.Find(strFind,pos);
if(pos == -1)
{
AfxMessageBox("Cannot find " + strFind);
}
else
{
m_ctrlEdit.SetFocus();
m_ctrlEdit.SetSel(pos,pos+lenStrFind);
curpos = pos;
pos = pos + lenStrFind;
}
}
//"Replace"
if(pFindReplaceDlg->ReplaceCurrent())
{
if(curpos >= 0)
{
m_ctrlEdit.SetFocus();
m_ctrlEdit.SetSel(curpos,curpos+lenStrFind);
m_ctrlEdit.ReplaceSel(strReplace);
m_ctrlEdit.SetSel(curpos,curpos+lenStrReplace);
pos = curpos + lenStrReplace;
}
}
//"Replace All"
if(pFindReplaceDlg->ReplaceAll())
{
UpdateData(TRUE);
m_strEdit.Replace(strFind,strReplace);
UpdateData(FALSE);
}
return 0;
}
(5)在自动生成按钮处理函数中添加代码
[cpp]
void CDialogTestDlg::OnCheck()
{
// TODO: Add your control notification handler code here
pos = 0;
curpos = -1;
//判断是否已经打开查找替换对话框,如果打开了,则使之成为活动窗口
if(pFindReplaceDlg)
{
pFindReplaceDlg->SetActiveWindow();
return;
}
//创建查找替换对话框
pFindReplaceDlg = new CFindReplaceDialog();
pFindReplaceDlg->Create(FALSE,NULL,NULL,FR_DOWN,this);
pFindReplaceDlg->ShowWindow(SW_SHOW);
}
补充:软件开发 , Vc ,