How can I create a button with default behavior in

2020-03-31 07:53发布

问题:

I have been trying to create a button with the default behavior i.e when the user press ENTER, the button is fired. I created the button with the WS_TABSTOP style and sent it the BM_SETSTYLE message with BS_DEFPUSHBUTTON has WPARAM parameter but it's still not working.

HWND hwnd_Ok = CreateWindow("button", "Ok", WS_VISIBLE | WS_CHILD | WS_TABSTOP, 285, 195, 70, 25, hwnd, (HMENU)OK_BUTTON, NULL, NULL);


SendMessage(hwnd_Ok, BM_SETSTYLE, (WPARAM)BS_DEFPUSHBUTTON, TRUE);

回答1:

I am trying to handle WM_GETDLGCODE for getting WM_KEYDOWN with VK_RETURN message in your control's WndProc. Sample code:

case WM_GETDLGCODE: {
  if(wParam==VK_RETURN) {
    return DLGC_WANTALLKEYS;
  }
}
break;


回答2:

The BS_DEFPUSHBUTTON is just a flag added to the button. The behavior you describe (along with lots of other field navigation behavior) is actually implemented by IsDialogMessage, which you get for free is a modal dialog box.

If you're trying to handle this in your own window class (or a modeless dialog), you can add IsDialogMessage to your message loop to get the dialog-style handling.



标签: winapi button