Tuesday, March 24, 2009

How to Trap Enter key on Edit Box

In order to trap the keypress you'll need to subclass the edit window.
Here's how to do it.
First, you'll need to store the original window proc in a global, so declare it as such:
FAR PROC DefEditProc;

Then you'll need to create a window proc to trap the message. Here's one that will do what you need:

LRESULT CALLBACK MyEditProc(HWND hDlg, UINT message,
WPARAM wParam, LPARAM lParam) {
switch(message) {
case WM_CHAR:
if( wParam == 13 ) {
/* User pressed ENTER -- do what you want here. */
return(0);
}
else return( (LRESULT)CallWindowProc
((WNDPROC)DefEditProc,hDlg,message,wParam,lParam) );
break;
default:
return( (LRESULT)CallWindowProc((WNDPROC)DefEditProc,
hDlg,message,wParam,lParam) );
break;
}
return(0);
}


Everything else below should occur when you're initializing the window containing the edit box:

Store the Edit window handle into EditWnd. You can do this several ways...if you created the edit window in a dialog box you can do this:
HWND EditWnd = GetDlgItem(hDlg,IDC_EDIT1);

Otherwise you should already have a handle to the edit window -- just store it in EditWnd. Then do the actual subclassing:

DefEditProc = (WNDPROC)GetWindowLong(EditWnd,GWL_WNDPROC);
SetWindowLong(EditWnd,GWL_WNDPROC,(long)MyEditProc);

No comments:

Post a Comment