DEV Community

海前 王
海前 王

Posted on

mfc 查找替换



void CMFCApplication3View::OnFindNext(LPCTSTR lpszFind, BOOL bNext, BOOL bCase)
{

        CEdit& editCtrl = GetEditCtrl();
        CString searchText = lpszFind;
        CString content;

        // 获取文本内容
        editCtrl.GetWindowText(content);

        // 获取当前选中范围
        int nStartChar, nEndChar;
        editCtrl.GetSel(nStartChar, nEndChar);

        int startPos = bNext ? nEndChar : 0; // 从当前位置开始查找
        int foundPos = -1;

        // 查找文本
        if (bCase)
            foundPos = content.Find(searchText, startPos);
        else
            foundPos = content.MakeLower().Find(searchText.MakeLower(), startPos);

        if (foundPos != -1)
        {
            // 设置选中的文本
            editCtrl.SetSel(foundPos, foundPos + searchText.GetLength());
            editCtrl.SetFocus();
        }
        else
        {
            AfxMessageBox(_T("Text not found. hh"));
        }


}



void CMFCApplication3View::OnReplaceSel(LPCTSTR lpszFind, BOOL bNext, BOOL bCase, LPCTSTR lpszReplace)
{
    CEdit& editCtrl = GetEditCtrl();
    CString findText = lpszFind;
    CString replaceText = lpszReplace;

    // 获取当前选中范围
    int nStartChar, nEndChar;
    editCtrl.GetSel(nStartChar, nEndChar);

    // 如果没有选中任何文本,则查找下一个匹配的文本
    if (nStartChar == nEndChar)
    {
        OnFindNext(lpszFind, bNext, bCase);
        editCtrl.GetSel(nStartChar, nEndChar);
    }

    // 获取选中的文本
    CString selectedText;
    editCtrl.GetWindowText(selectedText);

    // 确保选中的文本在当前选择范围内
    CString selectedTextInRange = selectedText.Mid(nStartChar, nEndChar - nStartChar);

    // 替换选中的文本
    if (selectedTextInRange.Compare(findText) == 0)
    {
        editCtrl.ReplaceSel(replaceText);
    }
    else
    {
        AfxMessageBox(_T("The selected text does not match the find text."));
    }
}
Enter fullscreen mode Exit fullscreen mode

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay