达内LOGO和北京达内网址达内科技培训项目:Java培训 3G培训 Android培训 软件测试培训北京达内服务电话
嵌入式培训
VC++查找替换对话框

    (1)设置全局变量

    [cpp] view plaincopyint curpos;

    int pos;

    CFindReplaceDialog *pFindReplaceDlg;

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

    [cpp] view plaincopystatic 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] view plaincopyBEGIN_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] view plaincopylong 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] view plaincopyvoid 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);

    }