Click here to Skip to main content
11,934,389 members (51,106 online)
Click here to Skip to main content
Add your own
alternative version


37 bookmarked

Using the CFindReplaceDialog class

, 9 Dec 2002
Rate this:
Please Sign up or sign in to vote.
How to use the CFindReplaceDialog dialog for text searching


This article is for MFC beginners and gives a general overview of using CFindReplaceDialog.

The problem we want to solve is how to allow the user to find any text string in their data. This article discusses the user interface, and not the actual searching algorithm.

One example of a good way of doing a long search is shown in RegEdit. It has a good UI for searches that may take a long time (cancel-search dialog).

Our example is designed for smaller data search. Note that when the time taken is noticable but not too long you can always use CWaitCursor.

We will demonstrate a way comparable with Wordpad search. First what will happen is a dialog will be displayed where user will enter a search string. It is not necessary to create our own Wordpad-like dialog in the resource editor because windows supports a standard one.

The API function FindText() creates a non-modal dialog which can communicate with its parent. (If you interested you can find details in help index under "common dialog boxes [Win32]/code examples/Finding text".)

We show how use CFindReplaceDialog which is an MFC class that calls FindText internally. Our FindDialog parent will be a tree-control (CMyTreeCtrl), but in general it can be any window type. This example ends at the FindWhatYouNeed() function call level.

In your handler (eg. in CMyTreeCtrl::OnFind()) you will create an instance of CFindReplaceDialog

ASSERT(m_pFindDialog == NULL);
m_pFindDialog = new CFindReplaceDialog();
m_pFindDialog->Create(TRUE, "Initial Text", NULL, FR_DOWN, this);

where m_pFindDialog is in my case class member of parent window CMyTreeCtrl

CFindReplaceDialog *m_pFindDialog;

This way it will display the find dialog in its default style. If you want you can change the dwFlags parameter of Create(). eg. FR_DOWN | FR_WHOLEWORD will check whole-word when the dialog starts. See "FINDREPLACE" help for all details.

When the dialog is opened the user can edit the text and change the checks (if you allow them to be shown). It's time to react to his actions.

CFindReplaceDialog sends a message to its parent. The ID of this message you can found by

UINT message = ::RegisterWindowMessage(FINDMSGSTRING);

Because ClassWizard knows nothing about this message we must add it manually. To MyTreeCtrl.h (parent window) add OnFindDialogMessage handler

     afx_msg void OnSomethingGeneratedByClassWizard();
     afx_msg LRESULT OnFindDialogMessage(WPARAM wParam, LPARAM lParam);


To MyTreeCtrl.cpp (parent window)

const UINT CMyTreeCtrl::m_FindDialogMessage = RegisterWindowMessage(FINDMSGSTRING);

     ON_REGISTERED_MESSAGE(m_FindDialogMessage, OnFindDialogMessage)

where m_pFindDialogMessage is defined in MyTreeCtrl.h as

static const UINT m_pFindDialogMessage;

Of course can be simple (not class member) variable:

static UINT FindDialogMessage = ::RegisterWindowMessage(FINDMSGSTRING);

     ON_REGISTERED_MESSAGE(FindDialogMessage, OnFindDialogMessage)

As you can see I wrote my own entry out of AFX_MSG_MAP so ClassWizard knows nothing about/has no problems with.

Now we have to write message handler:

LRESULT CMyTreeCtrl::OnFindDialogMessage(WPARAM wParam, LPARAM lParam)
    ASSERT(m_pFindDialog != NULL);

    // If the FR_DIALOGTERM flag is set,
    // invalidate the handle identifying the dialog box.
    if (m_pFindDialog->IsTerminating())
        m_pFindDialog = NULL;
        return 0;

    // If the FR_FINDNEXT flag is set,
    // call the application-defined search routine
    // to search for the requested string.
        //read data from dialog
        CString FindName = m_pFindDialog->GetFindString();
        bool bMatchCase = m_pFindDialog->MatchCase() == TRUE;
        bool bMatchWholeWord = m_pFindDialog->MatchWholeWord() == TRUE;
        bool bSearchDown = m_pFindDialog->SearchDown() == TRUE;

        //with given name do search
        FindWhatYouNeed(FindName, bMatchCase, bMatchWholeWord, bSearchDown);

    return 0;

It is more user friendly when you remember data read from the dialog and use it to modify parameters of next Create() call. You can add new class members to parent window class. If you will not use m_pFindDialog as a class member you can get it dynamicaly by

CFindReplaceDialog *pFindDialog = CFindReplaceDialog::GetNotifier(lparam);

When your tree control does not have the TVS_SHOWSELALWAYS flag set after find dialog opening user will not see actual line selection. Because of this we will set this flag before dialog's creation (CMyTreeCtrl::OnFind()):

if(GetWindowLong(GetSafeHwnd(), GWL_STYLE) & TVS_SHOWSELALWAYS)
	m_bRemoveShowSelAlwaysAtFindDialogExit = false;
	SetWindowLong(GetSafeHwnd(), GWL_STYLE,
	              GetWindowLong(GetSafeHwnd(), GWL_STYLE) | TVS_SHOWSELALWAYS);
	m_bRemoveShowSelAlwaysAtFindDialogExit = true; //return back at dialog exit

and in dialog termination (CMyTreeCtrl::OnFindDialogMessage()):

if (m_bRemoveShowSelAlwaysAtFindDialogExit)
	SetWindowLong(GetSafeHwnd(), GWL_STYLE,
	                            GWL_STYLE) & (~((LONG)TVS_SHOWSELALWAYS)));

If you want to enable it so that when you open the find dialog another window will have focus, then the find dialog or our parent/tree must switch TVS_SHOWSELALWAYS "more dynamicaly".

Logic requires that we do not open more find dialogs. Because of this, replace

ASSERT(m_pFindDialog == NULL);

by better code (if/return) or follow next.

We will close the find dialog when it loses focus. This is not very user friendly (eg. new mail notification will close the dialog) but it's good for a short example.

To do this I derived own CMyFindReplaceDialog class from CFindReplaceDialog. (Do not forget call the new CMyFindReplaceDialog in CMyTreeCtrl::OnFind()). Then I mapped the WM_ACTIVATE message in MyFindReplaceDialog.h

afx_msg void OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized);

in MyFindReplaceDialog.cpp add the message map entry:


and finally:

void CmyLayerDialog::OnActivate( UINT nState, CWnd* pWndOther, BOOL bMinimized )
    CFindReplaceDialog::OnActivate(nState, pWndOther, bMinimized );

    if(nState == WA_INACTIVE && IsTerminating() == false)
        //close dialog
        PostMessage(WM_COMMAND, IDABORT); //DestroyWindow();

The trick is not to call DestroyWindow(). The CFindReplaceDialog uses the protected class member m_szFindWhat in afxdlgs.h

TCHAR m_szFindWhat[128];

So do not exceed this size (or your text will be truncated).

In "FINDREPLACE" help you can find "The buffer should be at least 80 characters long." If you want (I do not know why) to replace this buffer by your own do not forget this point.

CFindReplaceDialog *pFindDialog = new CFindReplaceDialog();
pFindDialog->m_fr.lpstrFindWhat = MyBuffer;
pFindDialog->m_fr.wFindWhatLen =  _countof(MyBuffer);
pFindDialog->Create(TRUE, "Initial Text", NULL, FR_DOWN, this);

Do not forget MyBuffer must exist during whole find-dialog life so it can't be a local (stack) variable. (Easiest way is to derive CMyFindReplaceDialog from CFindReplaceDialog and create it as a class member.)

It is sometimes useful to make the find dialog "modal" (ie. make it impossible to switch to the parent until the dialog ends). It's easy: If we open it from a control in a dialog than add to the find-dialog Create() call:


and on IsTerminating()


(For safety you should take care of the case when Create() will be not successful.) If you have tree-control in a property page you must disable the whole sheet, not the actual page only:


and on IsTerminating()


This logic, with more if-s around, you can see in MFC CDialog::DoModal() in dlgcore.cpp or CPropertySheet::DoModal() in dlgprop.cpp.

Another, more complex example of using CFindReplaceDialog can be found in the MFC CRichEditView class. See the CRichEditView::OnEditFindReplace() function in the viewrich.cpp file.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Tibor Blazko
Software Developer (Senior)
Slovakia Slovakia
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
skyformat99@gmail.com21-Aug-13 20:45
memberskyformat99@gmail.com21-Aug-13 20:45 
GeneralMy vote of 5 Pin
Michael Haephrati1-Feb-12 11:29
memberMichael Haephrati1-Feb-12 11:29 
GeneralEditBox and Button using SendMessage Pin
mailtochandra2000@yahoo.com2-Feb-07 2:42
membermailtochandra2000@yahoo.com2-Feb-07 2:42 
GeneralFindNext Pin
Anonymous10-Jun-04 5:39
sussAnonymous10-Jun-04 5:39 
QuestionHow do I close the dialog? Pin
Anonymous30-Apr-04 2:06
sussAnonymous30-Apr-04 2:06 
AnswerRe: How do I close the dialog? Pin
Tibor Blazko30-Apr-04 2:29
memberTibor Blazko30-Apr-04 2:29 
QuestionHow to SendMessage? Pin
Adrian Gibbons21-Apr-04 10:46
memberAdrian Gibbons21-Apr-04 10:46 
AnswerRe: How to SendMessage? Pin
Tibor Blazko21-Apr-04 20:02
memberTibor Blazko21-Apr-04 20:02 
GeneralRe: How to SendMessage? Pin
Adrian Gibbons22-Apr-04 0:54
memberAdrian Gibbons22-Apr-04 0:54 
GeneralFind in a dialog box project based on CRcihEditCtrl Pin
Filomela5-Apr-04 22:08
memberFilomela5-Apr-04 22:08 
GeneralRe: Find in a dialog box project based on CRcihEditCtrl Pin
Tibor Blazko5-Apr-04 22:33
memberTibor Blazko5-Apr-04 22:33 
GeneralRe: Find in a dialog box project based on CRcihEditCtrl Pin
Filomela7-Apr-04 21:46
memberFilomela7-Apr-04 21:46 
GeneralRe: Find in a dialog box project based on CRcihEditCtrl Pin
Tibor Blazko21-Apr-04 19:58
memberTibor Blazko21-Apr-04 19:58 
GeneralFind Dialog Box Pin
sasan566-Sep-03 3:56
membersasan566-Sep-03 3:56 
GeneralRe: Find Dialog Box Pin
LynxDK9-Sep-03 20:10
memberLynxDK9-Sep-03 20:10 
GeneralRe: Find Dialog Box Pin
sasan5611-Sep-03 4:24
membersasan5611-Sep-03 4:24 
GeneralRe: Find Dialog Box Pin
LynxDK14-Sep-03 23:01
memberLynxDK14-Sep-03 23:01 
GeneralRe: Find Dialog Box Pin
Tibor Blazko11-Sep-03 6:40
memberTibor Blazko11-Sep-03 6:40 
GeneralFocus Problems while switching to another control Pin
Siegmund2-Jan-03 19:56
memberSiegmund2-Jan-03 19:56 
GeneralRe: Focus Problems while switching to another control Pin
Tibor Blazko2-Jan-03 20:07
memberTibor Blazko2-Jan-03 20:07 
QuestionFunction in the article NOT defined! Can use it? Pin
zhdleonid5-Dec-02 21:27
memberzhdleonid5-Dec-02 21:27 
AnswerRe: Function in the article NOT defined! Can use it? Pin
Tibor Blazko5-Dec-02 21:43
memberTibor Blazko5-Dec-02 21:43 
Generalmessages Pin
Anonymous2-Aug-02 11:24
sussAnonymous2-Aug-02 11:24 
GeneralRe: messages Pin
Tibor Blazko4-Aug-02 20:20
memberTibor Blazko4-Aug-02 20:20 
Generalcustomize Pin
Tibor Blazko6-Sep-01 4:20
memberTibor Blazko6-Sep-01 4:20 
GeneralDestroyWindow() according to MSDN Pin
Patrik Sjogren26-Feb-01 22:16
memberPatrik Sjogren26-Feb-01 22:16 
GeneralRe: DestroyWindow() according to MSDN Pin
David Walthall22-Oct-01 13:59
memberDavid Walthall22-Oct-01 13:59 
GeneralThank you Pin
andy21-Feb-01 8:51
memberandy21-Feb-01 8:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.151126.1 | Last Updated 10 Dec 2002
Article Copyright 2000 by Tibor Blazko
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid