1

让我解释一下我想要做什么。我有一个 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?
...
4

1 回答 1

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);
    }
}
于 2013-07-27T09:41:26.247 回答