Edit controls are very useful child controls because they provide a self-contained text editing area responding correctly to all key presses. As long as they have the input focus they can handle:
This is part of the automatic GUI that Windows developers are grateful for, and part of the reason that Windows programming, once understood, enables the programmer to build great applications relatively easily. There are a few things to watch out for, but the reader should grasp the fundamentals as a result of reading this article.
There are 2 kinds of edit box:
The difference between the 2 is that a multiline edit box can have scroll bars (managed by Windows), and the text wraps around automatically. A single line edit box is the default.
Creating an edit box requires a simple call to CreateWindow with the class set to "edit" and the style flags set according to whether the control should have scroll bars, scroll automatically, be single or multiline, etc. One style flag to be aware of is the ES_WANTRETURN flag which tells Windows that we do not want the enter key to perform the default action, but to insert a carriage return in the edit box.
This is only valid for multiline edit controls, and without it, carriage returns can not be inserted by the user. A simple example of a multiline edit box (like one would use for a Notepad style application) is as follows:
In the style flags, we could have omitted the WS_HSCROLL entry, but this would have created an automatically wrapping multiline edit control with no horizontal scroll bar. Without the ES_AUTOHSCROLL or ES_AUTOVSCROLL flags, we lose the automatic scroll bar interface, and also limit the text entry capabilities.
A simple single line edit control can be created with:
The chief differences are the lack of scroll bars, and the processing of the enter key. In both cases, the nEditID is assumed to be an identifier known to the application, the hwnd is the parent window handle, and the nClientWidth are nClientHeight are presumed to be set to useful values.
The GetDlgItemText message can be used to retrieve text from the edit control:
The szString parameter is an LPSTR, and nMax indicates the maximum number of characters that we can cope with. If the programmer needs to allocate memory dynamically for this, then a WM_GETTEXTLENGTH message can be sent to the control:
The return value from this is the number of characters in the text control.
Finally, the edit control can update the parent window as to when the contents are about to change. This happens through the WM_COMMAND message, where the EN_CHANGE identifier is set as the low word of the WPARAM parameter. The test for this, inside the WM_COMMAND case statement, is likely to look like:
Processing this notification allows the application to, for example, set a 'need to save' flag, or perform pre-edit control checks on the data.