user2257564
user2257564

Reputation: 63

WinApi Create unknown count of buttons dynamicly

Let me explain what I'm trying to do. I have a config.ini file with btn_total=10 (for example). I'm trying to write a program using pure WinApi (C) to create a Dialog and btn_total buttons on it. Each button should do MessageBox to show it's name (for example). I mean every button should do same job with different data.

I did it easily with C# forms:

...
int top = 5;
int left = 5;
int btnH = 22, btnW = 200;

for (int i = 1; i <= btn_total; i++)
{
    Button button = new Button();
    button.Name = i.ToString();
    button.TabStop = false;
    button.FlatStyle = FlatStyle.Standard;
    button.Left = left;
    button.Top = top;
    button.Text = i.ToString();
    button.Size = new Size(btnW, btnH);
    button.Click += (s, e) =>
    {
        MessageBox.Show(i.ToString());
    };
    frmMain.Controls.Add(button);
    top += button.Height + 1;
}
frmMain.Size = new Size(btnW + 15, top + btnH + 10);
...

but how can I do same using VC++ pure WinApi (CreateWindowEx and so on)? Thanks in advice!!

Added: I know that I have to do this in loop also. like

HWND hBtn[100]; //for example array of HWNDs
for(int i=0; i<btn_total; i++)
{
    // "i" is a button ID. How to switch it right (in WM_COMMAND)?
    hBtn[i] = CreateWindow(...create button...,(HMENU)i,...); 
}
...
case WM_COMMAND:

    // HOW SHOULD I PROCEED PRESSED BUTTON?
    // Using kind of switch or something?
...

Upvotes: 1

Views: 230

Answers (1)

Edward Clements
Edward Clements

Reputation: 5132

Create buttons:

#define IDC_BUTTON_START    1000
int x, y;
TCHAR szButtonText[64];
for (int i = 0; i < btn_total; i++)
{   // set up szButtonText = text on the button
    // set up x and y = coordinates for the button
    CreateWindow("BUTTON", szButtonText, WS_CHILD|WS_VISIBLE, x, y, 40, 25, hDlg, (HMENU)IDC_BUTTON_START+i, hInst, 0);
}

Button press message handling:

case WM_COMMAND:
{   WORD nIDCmd = LOWORD(wParam);
    if (nIDCmd >= IDC_BUTTON_START && nIDCmd < IDC_BUTTON_START + btn_total)
    {   WORD nIDBtn = nIDCmd - IDC_BUTTON_START;
        // process msg for btn[nIDBtn]
        TCHAR szBtnText[64];
        GetWindowText(GetDlgItem(hDlg, nIDCmd), szBtnText, _countof(szBtnText));
        MessageBox(hDlg, szBtnText, _T("Button Clicked"), MB_OK|MB_ICONINFORMATION);
    }
}

Upvotes: 2

Related Questions