2014-12-02 101 views
1

當我在TextBox中輸入一個值,然後單擊按鈕時,MessageBox必須顯示輸入的值而不是空的MessageBox。 那麼如何在點擊按鈕後在MessageBox上顯示輸入值?獲取TextBox值並將其顯示爲MessageBox WinApi

#include <windows.h> 

LRESULT CALLBACK WndProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam) { 

HWND TextBox; 
char textSaved[20]; 
    switch(Message) { 
     case WM_CREATE: 

     TextBox = CreateWindow("EDIT", 
           "", 
           WS_BORDER | WS_CHILD | WS_VISIBLE, 
           10,10,300,20, 
           hwnd, NULL, NULL, NULL); 
     CreateWindow("BUTTON", 
        "Go", 
        WS_VISIBLE | WS_CHILD | WS_BORDER, 
        420, 10, 70, 20, 
        hwnd, (HMENU) 1, NULL, NULL); 

     break; 

     case WM_COMMAND: 

      switch(LOWORD(wParam)) 
      { 
       case 1: 

       int gwtstat =0; 
       gwtstat = GetWindowText(TextBox, &textSaved[0], 20); 
       ::MessageBox(hwnd, textSaved, textSaved, MB_OK); 
       break; 
      } 

     break; 

     case WM_DESTROY: { PostQuitMessage(0);break;} 
     default: 
      return DefWindowProc(hwnd, Message, wParam, lParam); 
    } 
    return 0; 
} 
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { 
    WNDCLASSEX wc; 
    HWND hwnd; 
    MSG Msg; 
    memset(&wc,0,sizeof(wc)); 
    wc.cbSize  = sizeof(WNDCLASSEX); 
    wc.lpfnWndProc = WndProc; 
    wc.hInstance  = hInstance; 
    wc.hCursor  = LoadCursor(NULL, IDC_ARROW); 
    //HBRUSH brush = CreateSolidBrush(RGB(0, 0, 255)); 
    wc.hbrBackground = CreateSolidBrush(RGB(20, 60, 12));//(brush)(COLOR_WINDOW+1); 
    wc.lpszClassName = "WindowClass"; 
    wc.hIcon   = LoadIcon(NULL, IDI_APPLICATION); 
    wc.hIconSm  = LoadIcon(NULL, IDI_APPLICATION); 
    if(!RegisterClassEx(&wc)) { 
     MessageBox(NULL, "Window Registration Failed!","Error!",MB_ICONEXCLAMATION|MB_OK); 
     return 0; 
    } 
    hwnd = CreateWindowEx(WS_EX_CLIENTEDGE,"WindowClass","Caption",WS_VISIBLE|WS_OVERLAPPEDWINDOW, 
     CW_USEDEFAULT, 
     CW_USEDEFAULT, 
     640, 
     480, 
     NULL,NULL,hInstance,NULL); 

    if(hwnd == NULL) { 
     MessageBox(NULL, "Window Creation Failed!","Error!",MB_ICONEXCLAMATION|MB_OK); 
     return 0; 
    } 

    while(GetMessage(&Msg, NULL, 0, 0) > 0) { 
     TranslateMessage(&Msg); 
     DispatchMessage(&Msg); 
    } 
    return Msg.wParam; 
} 

回答

3

聲明HWND TextBox;WndProc的內部意味着其值復位(未初始化值)每次你的窗口過程被調用時。如果你想保存你需要的值,使變量static或全局。

+0

謝謝你已經解決了我的問題! – 2014-12-02 23:24:42

2

首先,你需要得到文本框中的文字,在你的情況下,它沒有ID,則因爲在你的情況下使用此代碼創建一個ID文本框的HWND文本框是重置每次你的窗口過程被稱爲時間:

CreateWindowW(L"EDIT", L"", WS_BORDER | WS_CHILD | WS_VISIBLE, 10,10,300,20, hwnd, (HMENU)2, NULL, NULL); 

現在你的文本框有一個ID,我們不需要HWND TextBox控件,使用函數GetDlgItem爲獲取文本框和GetWindowTextW爲獲取文本框的在wchar_t陣列的文本和存儲:

case 1: 
    int len = GetWindowTextLengthW(GetDlgItem(hwnd, 2)) + 1; 
    wchar_t text[len]; 
    GetWindowTextW(GetDlgItem(hwnd, 2), text, len); 
    MessageBoxW(NULL, text, L"MsgFromTextBox", MB_OK); 
相關問題