CEditWithButton is a simple edit control class derived from
CEdit (MFC) that looks like the iTunes Find Edit Control. The edit control can
show an icon and a button. This class can be used when ever an edit control and
a button go together. Example: Browsing a file, folder; Finding etc.
This is my first article at CodeProject. For years I have only used great
code from CodeProject. I thank you all for sharing excellent code. Thank you
very much. I hope to write more articles in the near future. Please do not
hesitate to comment on my code. I wish to learn and improve.
Thanks to Johan Rosengren for his article An edit
box with an icon. He revealed the affect of
on an edit control in this article.
Using the code
1. Defining the class
Create an edit control in your dialog box and add a variable of type
CEditWithButton. If you have already added a variable which is of
CEdit, then you can just rename CEdit to
CEditWithButton and #include "EditWithButton.h" at the top of the dialog header
class CFindEditDlg : public CDialog
2. Using the class
The class accepts 2 bitmaps. The first bitmap is drawn as a background of the
edit control when it is empty. The second bitmap is drawn as a background when
the edit control contains some text in it. The first bitmap is a background
without the button. The second bitmap is the background with the button.
Next, we need to set the edit area and the button area. We need to do this
because only part of the edit control is editable. The left and right area are
covered by the icon (magnifying glass in our case) and the button (x button in
Next, when the user clicks on the button, this message is sent to the the
owner in order to let it handle the button click event.
If the button exists always (even if the edit control does not have any text)
then you need to set this flag to
TRUE using the
SetButtonExistsAlways method. This enables the class to send the
button click even even when there is no text in the edit control.
case, we have set to FALSE because we are using it as a find edit control where
in the button is hidden when the edit control is empty.
Points of Interest (Must Read)
- In order to set the edit area for an edit control, we use the
CEdit::SetRect method internally. This method succeeds only if the
edit control has the multi-line style set (
ES_MULTILINE). If you
are inserting the edit control in a dialog, make sure the multi-line property is
set to True using the resource editor. Also make sure that
ES_WANTRETURN is set to False.
- If you are creating the edit control dynamically you must set the edit
control's font explicitly in order to make it work perfectly. See the following
- 3rd August 2006: Updated the code so that the edit control can be created
- 2nd August 2006: First public release