VC++查找替换对话框

(1)设置全局变量

	int curpos;
	int pos;
	CFindReplaceDialog *pFindReplaceDlg;


(2)为了使父窗口知道查找/替换请求,必须使用RegisterWindowMessage函数,它的返回值是应用实例唯一的消息号。

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 theFind Next, Replace, or Replace All button, or closes the dialog box.

(3)在源文件里面将消息映射函数与WM_FINDMESSAGE消息关联

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

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 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)在自动生成按钮处理函数中添加代码

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);
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值