【问题标题】:WinApi Create unknown count of buttons dynamiclyWinApi 动态创建未知数量的按钮
【发布时间】:2013-07-27 07:27:03
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    创建按钮:

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

    【讨论】:

    • 如何处理 btn[nIDBtn] 的 msg?
    • 取决于您在单击 btn 时要执行的操作,通过“处理 msg for”,我的意思是“为单击执行操作”
    • 我有 10 个按钮,每个按钮都应该显示带有 btn 名称作为主题的 MessageBox。
    • 啊哈,我明白了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-08-02
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-08
    • 2015-05-28
    • 1970-01-01
    相关资源
    最近更新 更多