user2768609
user2768609

Reputation: 23

SendMessage(..., CB_GETCURSEL, 0, 0) always returns 0 (Winapi)

First of all forgive me, but I am total newb. I am trying to write a program that recognize my combobox selection when I click on the screen (I pick the item I want to place there). However I cannot, because the SendMessage function always returns 0. How can I get the proper result?

HWND g_Combobox;

/* ... */

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    /* ... */

    switch (message)
    {
    case WM_CREATE:
    {
       HWND g_Combobox = CreateWindowEx( WS_EX_CLIENTEDGE, L"COMBOBOX", NULL, WS_CHILD | WS_VISIBLE | WS_BORDER |
            CBS_DROPDOWNLIST, 5, 25, 180, 200, hWnd, (HMENU) ID_MYCOMBO, hInst, NULL );
       SendMessage( g_Combobox, CB_ADDSTRING, 0,( LPARAM ) L"item 1" );
       SendMessage( g_Combobox, CB_ADDSTRING, 0,( LPARAM ) L"item 2" );
       SendMessage( g_Combobox, CB_ADDSTRING, 0,( LPARAM ) L"item 3" );

    /* ... */
    }
        break;
    case WM_LBUTTONDOWN:
    {
             switch (SendMessage(g_Combobox, CB_GETCURSEL, 0, 0))
             {
             case 0: //always picks this one
                 MessageBox( NULL, L"0", L"Oh noes!", MB_ICONEXCLAMATION );
                 break;
             default:
                 MessageBox( NULL, L"something diffrent than 0", L"Yeah...", MB_ICONEXCLAMATION );
                 break;
             }
    }

What am I doing wrong?

Upvotes: 1

Views: 2998

Answers (1)

Alex F
Alex F

Reputation: 43311

HWND g_Combobox = CreateWindowEx(...

Replace with:

g_Combobox = CreateWindowEx(...

Your current code fills local variable, leaving global variable unchanged. This is why SendMessage working with global variable gives unexpected results.

To solve such kind of problems in the future:

  1. Use debugger.

  2. Use maximal available compiler warning level.

Upvotes: 3

Related Questions