tags:

views:

331

answers:

3

Hi, im starting with Win32 api, im adding a button control to my main window with the flowing code:


 HWND boton = CreateWindow(
    "BUTTON",   //
    "Caption",       // 
    WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,  // Styles.
    250,         // x position.
    10,         // y position.
    100,        // Button width.
    40,        // Button height.
    hwnd,       // Parent window.
    NULL,       // No menu.
    (HINSTANCE)GetWindowLong(hwnd, GWL_HINSTANCE),
    NULL);      // Pointer not needed.

how can i assign it an id, so i can get the message on the loop, in the message loop im trying to catch the message as WM_COMMAND but i don't get any result i've tried with WM_NOTIFY too.

+2  A: 

In fact, you do not need to specify an ID for the button. The problem is your code is missing a style bit to CreateWindow().

You must specify the style BS_NOTIFY for the parent window to receive notifications from Button controls.

You will then receive window message WM_COMMAND with (HIWORD(w_param) == BN_CLICKED) every time your button is clicked. See the BN_CLICKED documentation for more.

Using a control ID is unnecessary because the BN_CLICKED message will provide you with the control's window handle. Because you are already required to keep track of the window handle in order to properly call DestroyWindow when you receive WM_DESTROY comparing the button's window handle is just as easy as using a control ID.

Heath Hunnicutt
Yeah, you're right, I'm sorry for stealing your thunder. Have an up-vote. It's only 5 points short of an accept.
dreamlax
You dont need to destroy the window in WM_DESTROY. Owned windows are automatically destroyed when their owner is destroyed. If NULL was being passed to parameter 8 then sure.
Chris Becke
A: 

To assign it an ID, you have to use the hMenu parameter. If you have specified that the window will be a child (i.e. with WS_CHILD), the hMenu parameter will be interpreted as an integer ID for the window. Also, provide the BS_NOTIFY style.


HWND boton = CreateWindow (
    "BUTTON", 
    WS_TAPSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON | BS_NOTIFY,
    250, 10, 100, 40,
    hwnd,
    (HMENU)101,  // This becomes the Control ID
    (HINSTNACE)GetWindowLong(hwnd,GWL_HINSTANCE),
    NULL);

EDIT: Special shout goes out to Heath Hunnicutt for the info on BS_NOTIFY.

dreamlax
Hey maybe I should update my answer with the info on how to pass it in as an ID... :-/
Heath Hunnicutt
BS_NOTIFY is only necessary if you want to receive notifications other than BN_CLICKED.
Chris Becke
A: 

To set the window id, pass it in as if it were an HMENU:

(HMENU) nChildID

Jeff Paquette