• home
  • forum
  • my
  • kt
  • download
  • Create a Checkbox and track check/uncheck events

    Author: 2007-09-06 11:05:22 From:

    Checkboxes are also created using BUTTON class, the difference is just the style, while creating a push-button we supplied style BS_PUSHBUTTON, but when we need to create a checkbox we supply style BS_AUTOCHECKBOX.
    See following example and enclosed comments carefully.


    #include <windows.h>

    int checkbox_id = 156;
    //prototype of window procedure
    LRESULT WINAPI myProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);

    int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
    {
    MSG msg;
    HWND myDialog = CreateWindowEx(
    0,WC_DIALOG,"My Window",WS_OVERLAPPEDWINDOW | WS_VISIBLE,
    400,100,200,200,NULL,NULL,NULL,NULL
    );
    //create the checkbox
    HWND txt = CreateWindowEx(
    0,"BUTTON","Check and uncheck me",BS_AUTOCHECKBOX | WS_VISIBLE | WS_CHILD,
    10,50,170,25,myDialog,(HMENU)checkbox_id,NULL,NULL
    );

    SetWindowLong(myDialog, DWL_DLGPROC, (long)myProc);

    while(GetMessage(&msg,NULL,0,0)) {
    TranslateMessage(&msg);
    DispatchMessage(&msg);
    }

    return 0;
    }

    LRESULT WINAPI myProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
    {
    if(message == WM_CLOSE)
    PostQuitMessage(0);

    //check if checkbox was check or unchecked
    if(message==WM_COMMAND && LOWORD(wParam)==checkbox_id)
    {
    //First get handle of checkbox by casting lParam to HWND
    HWND checkbox_handle = (HWND)lParam;
    //send message BM_GETCHECK to check box to retrieve its current state
    int state = SendMessage(checkbox_handle,BM_GETCHECK,0,0);

    if(state == BST_CHECKED) //yes it is checked
    MessageBox(hwnd,"It hs checked","Message",0);
    else
    ;//it has been Unchecked
    }

    return 0;
    }

    discuss this topic to forum

    relation tutorial

    No relevant information

    Category

      Basics (9)

    New

    Hot