Maras
Maras

Reputation: 982

Dealing with a table of buttons (WinAPI)

I'm quite new to WinAPI, so I sometimes make a lot of basic mistakes. You've been warned, let's move to my problem :P/

I want to make something like a grid. If the user click one of the grid's fields, there should appear a bitmap. I've made a bitmap of field that I want to use as a button. At the start user inputs a size of the grid, so I've made a dynamic library of buttons with that bitmap. Unfortunately, I have no idea how to deal with them when they are clicked. Here's my code:

//there I create my window. I also make a global variable bool* table and HWND next.
table = new bool[x*y];
for (int i = 0; i < x*y; ++i)
    table[i] = 0;
//the table represents if the fields are already filled or not.

HWND* buttons = new HWND[x*y];
next = CreateWindowEx(4, _T("BUTTON"), _T("MOVE"), WS_CHILD | WS_VISIBLE, x * 12 - 25, (y + 4) * 25 - 90, 100, 50, hwnd, NULL, hThisInstance, NULL);

for (int i = 0; i < x; ++i)
{
    for (int j = 0; j < y; ++j)
    {
        buttons[i + j * x] = CreateWindowEx(0, _T("BUTTON"), NULL, WS_CHILD | WS_VISIBLE | BS_BITMAP, 0 + i * 25, 0 + j * 25, 25, 25, hwnd, NULL, hThisInstance, NULL);
        SendMessage(przyciski[i + j * x], BM_SETIMAGE, (WPARAM)IMAGE_BITMAP, (LPARAM)field);
    }
}

And now in WindowProcedure():

switch (message)
    {
        case WM_COMMAND:
            if ((HWND)lParam == next) /* there will be some code in the future ;) */;
            else
            {
                //So here I need to set correct the value in table to 1
                //I have a handle to clicked button (HWND)lParam, but I don't know how to get it's position in the table
            }
            break;

I tried to do some struct with HWND and int x, y, but I still don't know how to manage this. BTW, the code might look very old, I need to create an app that Windows XP can run (it's a project for school, do not inquire :P) and in addition I use a very old tutorial.

Upvotes: 0

Views: 268

Answers (1)

Barmak Shemirani
Barmak Shemirani

Reputation: 31609

Assign an ID for each button using the HMENU parameter. The ID cannot be zero, therefore add an arbitrary offset, for example 100:

buttons[i + j * x] = CreateWindowEx(0, _T("BUTTON"), NULL, 
    WS_CHILD | WS_VISIBLE | BS_BITMAP, 0 + i * 25, 0 + j * 25, 25, 25, 
    hwnd, HMENU(100 + i + j * x), hThisInstance, NULL);

You can also extract the row and column from button_index, knowing the total rows and total columns. Example:

case WM_COMMAND:
{
    if (HIWORD(wParam) == BN_CLICKED)
    {
        int id = LOWORD(wParam);
        int button_index = id - 100;
        if (button_index >= 0 && button_index < x * y)
        {
            int row = button_index / x;
            int column = button_index % x;
            ...
        }
        ...
    }
    break;
}

Upvotes: 1

Related Questions