2012-08-07 45 views
0

我正在用C++/WINAPI编写我的第一个简单程序,带有很多复选框和一些编辑字段,它们将在按钮按下时设置一些计算。我所有的复选框合作,通过个案/存储信息,即从编辑字段获取值(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未定义的地方,但我不知道如何将定义发送到此范围,或者我应该在哪里读取和存储编辑字段值。

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

+1

即使这将从右侧的控件读取,它会导致内存覆盖: LPSTR edit1; GetWindowText(editControl1,edit1,100); 您需要在GetWindowText可以放置文本的位置创建一个缓冲区。上面的edit1只是一个未初始化的指针。 TCHAR edit1 [100]; (edit1,edit1,sizeof(edit1)/ sizeof(edit1 [0])); – 2012-08-07 05:12:07

回答

0

您的编辑字段的ID是否正确?然后你可以使用GetDlgItem。

editControl1 = GetDlgItem(hwnd, CONTROL_ID_1); 

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

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