从编辑字段(C++WINAPI)获取值

Getting value from edit field (C++ WINAPI)

本文关键字:获取 C++WINAPI 编辑 字段      更新时间:2023-10-16

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

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

但我认为编辑字段不能像按下按钮那样作为大小写语句,因为一旦用户想要更改多少次,就必须在最后读取值。我上网查看了一下,试图使用SendMessage(hwnd,…)和GetWindowText(hwnd…)函数将WM_GETTEXT命令发送到编辑字段,并将其存储到lpstr字符串中,但我在这两个函数中都遇到了相同的问题-编辑字段的hwnd没有在发送WM_GETEXT命令的作用域中声明,我不知道如何将其发送到那里。以下是我的程序中使用的结构的概述,它来自于我正在使用的一些教程的混合:

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未定义的地方,但我不知道如何将定义发送到这个范围,也不知道我应该在哪里读取和存储编辑字段值。

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

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

editControl1 = GetDlgItem(hwnd, CONTROL_ID_1);

GetDlgItem的名称不正确,它不只是在对话框中工作。它使用子窗口的ID从父窗口获取任何子窗口的句柄。

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