如何在Gui win32编程中使用静态标签和按钮

时间:2015-12-07 13:07:51

标签: c++ winapi

我正在学习win32编程。为了更好地理解win32框架中的编程概念,我将编写一个简单的计算器。我设计了它的视图,但现在我想要当用户点击按钮时,例如按钮1,它的数字显示在静态标签上。我使用了SetDlgItemText,但它不起作用。我把程序的图片放在下面:

enter image description here

我有IDC_Button01到IDC_Button12的ID为12的按钮,我有一个带有IDC_Display ID的静态标签元素。我把我的代码放在下一节中。

#include <windows.h>
#include <tchar.h>
#include "resource.h"

#pragma comment(linker, \
  "\"/manifestdependency:type='Win32' "\
  "name='Microsoft.Windows.Common-Controls' "\
  "version='6.0.0.0' "\
  "processorArchitecture='*' "\
  "publicKeyToken='6595b64144ccf1df' "\
  "language='*'\"")
#pragma comment(lib, "ComCtl32.lib")

// Step 4: the Window Procedure
INT_PTR CALLBACK DialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
const char g_szClassName[] = "myWindowClass";

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    HWND hDlg;
    BOOL ret;
    MSG msg;

    hDlg = CreateDialogParam(hInstance, MAKEINTRESOURCE(IDD_MainWindow), 0, DialogProc, 0);
    ShowWindow(hDlg, nCmdShow);

    // Step 3: The Message Loop
    while ((ret = GetMessage(&msg, 0, 0, 0)) != 0) {
        if (ret == -1) /* error found */
            return -1;
        if (!IsDialogMessage(hDlg, &msg)) {
            TranslateMessage(&msg); /* translate virtual-key messages */
            DispatchMessage(&msg); /* send it to dialog procedure */
        }
    }
    return msg.wParam;
}

// Step 4: the Window Procedure

INT_PTR CALLBACK DialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case IDCANCEL:
            SendMessage(hDlg, WM_CLOSE, 0, 0);
            return TRUE;
        case IDOK:
            MessageBox(hDlg, TEXT("Program will quit."), TEXT("Message"), MB_ICONQUESTION);
            PostQuitMessage(0);
            return TRUE;
        }
        break;
    case IDC_BUTTON1:
        SetDlgItemText(hDlg, IDC_Display, TEXT("1"));
    case WM_CLOSE:
        if (MessageBox(hDlg, TEXT("Close the program?"), TEXT("Close"), MB_ICONQUESTION | MB_YESNO) == IDYES)
        {
            DestroyWindow(hDlg);
        }
        return TRUE;

    case WM_DESTROY:
        PostQuitMessage(0);
        return TRUE;
    }

    return FALSE;
}

1 个答案:

答案 0 :(得分:1)

资源ID不是有效Windows messageWM_COMMAND用于向父窗口发送通知

INT_PTR CALLBACK DialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
  ..
  case WM_COMMAND:
    switch (LOWORD(wParam))
    {
    case IDC_BUTTON1: {
      SetDlgItemText(hDlg, IDC_Display, TEXT("1"));
      return TRUE;
    } break;
    break;

wParam设置为控件标识符。