WinApi动态创建未知的按钮数

时间:2013-07-27 07:27:04

标签: winapi visual-c++ user-interface runtime

让我解释一下我要做的事情。 我有一个btn_total = 10的config.ini文件(例如)。 我正在尝试使用纯WinApi(C)编写一个程序来创建一个Dialog和btn_total按钮。每个按钮都应该使用MessageBox来显示它的名称(例如)。我的意思是每个按钮都应该用不同的数据做同样的工作。

我用C#表单轻松完成了:

...
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);
...

但是如何使用VC ++纯WinApi(CreateWindowEx等)来做同样的事情?谢谢你的建议!!

添加了: 我知道我必须在循环中也这样做。像

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?
...

1 个答案:

答案 0 :(得分:2)

创建按钮:

#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);
}

按钮按下消息处理:

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);
    }
}