2012-08-07 52 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的方式會導致程序崩潰。