0

我正在用 C++/WINAPI 编写我的第一个简单程序,其中有很多复选框和一些编辑字段,它们将在按下按钮时设置一些计算。我所有的复选框都通过个别案例工作/存储信息,即

switch (msg)
{
    ...
    case WM_COMMAND:
    {
        switch (wParam)
        {
            case IDBC_BoxCheck1:
            {...}
            case IDBC_BoxCheck2:
            {...}
            ...
        } ...

...但我认为编辑字段不像按下按钮那样作为 case 语句起作用,因为一旦用户想要多次更改该值,就必须在最后读取该值。我在网上查看并尝试使用 SendMessage(hwnd, ...) 和 GetWindowText(hwnd, ...) 函数将 WM_GETTEXT 命令发送到编辑字段并将其存储到 lpstr 字符串,但我遇到了同样的问题与他们两个 - 编辑字段的 hwnd 未在发送 WM_GETTEXT 命令的范围内声明,我不知道如何到达那里。以下是我的程序中使用的结构的概述,它来自我正在使用的一些教程的混合:

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch (msg)
    {
        case WM_CREATE:
        {
            return OnCreate(hwnd, reinterpret_cast<CREATESTRUCT*>(lParam));
            // OnCreate is a sub function that handles the creation of all the buttons/controls,
            // since there are so many of them, with the format:
            // HWND editControl1 = CreateControl(...); // CreateControl being another sub fnct
                                                       // that creates edit field ctrls
                                                       // editControl1 is the hwnd I'm trying
                                                       // to read the value from
            // HWND checkControl1 = CreateButton(...); // Creates button ctrls, including ck box
            ...
        }
        ...
        case WM_COMMAND:
        {
            switch (wParam)
            {
                case IDBC_BoxCheck1:    // These control IDs are defined at the top of the file
                {
                   LPSTR Check1;
                   StoreInfo(Check1);   // Just a sub fnct to store info for later calculations
                }
                case IDBC_BoxCheck2:
                {
                    LPSTR Check2;
                    StoreInfo(Check2);
                } // etc... there are 20 or so check boxes/buttons
                case IDBC_Calculate:    
                {
                    LPSTR edit1;
                    GetWindowText(editControl1, edit1, 100); // or SendMessage(editControl1, ...)
                    // This kicks out the error of editControl1 not being declared in this scope
                    StoreInfo(edit1);
                    // Calculation function goes here
                } ...
            } ....
        }
        default: DefWindowProc(hwnd, msg, wParam, lParam);
    }
}

IDBC_Calculate 是计算运行前按下的最后一个按钮。我认为从编辑字段读取和存储值的最佳位置是在按下此按钮之后,就在调用计算函数之前,但与相同的命令相关联。这是 hwnd editControl1 未定义的地方,但我不知道如何将定义发送到此范围,或者我应该在哪里读取和存储编辑字段值。

任何有关从这些编辑字段中获取值到我的其他功能的帮助或指示将不胜感激!我在各种教程/课程中看到了许多不同的方法来检查按钮状态,所以我很想知道是否有更好的方法来做我上面写的一般。

4

1 回答 1

1

您的编辑字段有 ID 对吗?然后你可以使用GetDlgItem。

editControl1 = GetDlgItem(hwnd, CONTROL_ID_1);

GetDlgItem名字不好,它不仅在对话框中起作用。它使用子窗口的 ID 从父窗口获取任何子窗口的句柄。

Anders K 说的是正确的。您使用 GetWindowText 的方式会使您的程序崩溃。

于 2012-08-07T06:30:27.830 回答