Add negative values for CreateWindow macro in C++

Viewed 337

I created the textbox using CreateWindow API in Windows GUI Programming as follows,

CreateWindow( TEXT("EDIT"),
            TEXT(""),
            WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL | WS_DLGFRAME | ES_RIGHT,
            x, y, w, h,
            hwnd_,
            (HMENU)0,
            GetWindowInstance( hwnd_ ),
            0 );

When I use ES_NUMBER edit control style, it is only allowed to put digits into the edit control. But I cannot put negative values as -123.

Is there way to support to only integers within negative values in edit control? Can any one help for that me?

1 Answers

The ES_NUMBER style should be better called ES_DIGITSONLY. It accepts only digits as keyboard input.

If you want to use the Windows edit control accepting digits and signs, you have to subclass it. That means, you exchange the default window procedure of your edit control with your own window procedure. Your window procedure implements the new features of the edit control, anything else is passed to the default window procedure of the edit control (not DefWindowProc() !).

Here is an example in old-style C (because you used the Win32 API):

WNDPROC PreviousEditProc;

LRESULT  CALLBACK EditSubclassProc( HWND hWnd, UINT uMessage, WPARAM wParam, LPARAM lParam ) {

const TCHAR* ACCEPTED_CHARS = TEXT("0123456789+-");
TCHAR    c;

    switch( uMessage ) {
        case WM_CHAR:
            c = (TCHAR) wParam;
            if( _tcschr( ACCEPTED_CHARS, c ) == nullptr )
                return( 0 );
            break;
    } 

    return( CallWindowProc( PreviousEditProc, hWnd, uMessage, wParam, lParam ) );
}

The subclass the edit control, you have to change to window procedure and save the previous procedure:

HWND hEdit;

hEdit = CreateWindow( TEXT("EDIT"),
            TEXT(""),
            WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL | WS_DLGFRAME | ES_RIGHT,
            x, y, w, h,
            hwnd_,
            (HMENU)0,
            GetWindowInstance( hwnd_ ),
            0 );
PreviousEditProc = (WNDPROC) SetWindowLong( hEdit, GWL_WNDPROC, (LPARAM) EditSubclassProc );

Remarks:

Your may subclass several edit controls, using the code above, but you cannot subclass an edit control twice with the same subclass procedure (PreviousEditProc will be overwritten by itself).

The TCHAR type is wchar_t, if you compile your project with Unicode enabled or char else. You may want to use char or wchar_t directly.

The string literal ACCEPTED_CHARS contains all acceppted characters. For a longer list you may use isdigit(), ischar() etc. instead of the _tcsstr() function.

Related