In addition to handling the EN_CHANGE notification, you also have the option to subclass this window. This will allow you to limit valid keystrokes and only allow numbers, periods, etc. The following example shows how to create an edit control, subclass it, and filter the input so that only certain characters are allowed. It does not handle operations such as pasting from the clipboard, so you want to expand it to fit your specific requirements.
The advantages of this approach are that you do not need to add additional code to the parent window to filter the edit control. This allows you to use it in all applications without duplicating a large amount of code. Another advantage is the elimination of possible flickering that occurs when updating the contents of the control to remove unwanted characters.
static WNDPROC OriginalEditCtrlProc = NULL; LRESULT CALLBACK MyWindowProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { if(uMsg == WM_CHAR) { // Make sure we only allow specific characters if(! ((wParam >= '0' && wParam <= '9') || wParam == '.' || wParam == VK_RETURN || wParam == VK_DELETE || wParam == VK_BACK)) { return 0; } } return CallWindowProc(OriginalEditCtrlProc, hwnd, uMsg, wParam, lParam); } void CreateCustomEdit(HINSTANCE hInstance, HWND hParent, UINT id) { HWND hwnd; hwnd = CreateWindowEx( WS_EX_CLIENTEDGE, _T("EDIT"), _T(""), WS_VISIBLE | WS_CHILD | WS_BORDER | ES_LEFT, 0, 0, 200, 40, hParent, reinterpret_cast<HMENU>(id), hInstance, NULL); if(hwnd != NULL) { // Subclass the window so we can filter keystrokes WNDPROC oldProc = reinterpret_cast<WNDPROC>(SetWindowLongPtr( hwnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(MyWindowProc))); if(OriginalEditCtrlProc == NULL) { OriginalEditCtrlProc = oldProc; } } }
source share