先随便新建一个项目,比如这个控制台应用:
项目右键添加资源:
选dialog,如下图:
然后双击资源文件,如下图:
右键查看属性:
记住这个id,后面会用到,另这个id可以手动修改。
CPP文件写如下代码:
文字版:
#include <iostream>
#include <windows.h>
#include "resource.h"
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return 0;
}
int main()
{
std::cout << "Hello World!\n";
DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_DIALOG1), NULL, (DLGPROC)WndProc);
}
代码里的IDD_DIALOG1,就是上上图里的那个ID。
然后运行一下,可以出现结果:
目前按键还没作用,现在增加按键响应。
右键这个按键,然后选属性,可以看到这个按钮的ID,如下图:
这个ID也可以手动修改。
然后修改代码,如下:
#include <iostream>
#include <windows.h>
#include "resource.h"
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (msg == WM_COMMAND) {
auto id = LOWORD(wParam);
if (id == IDOK)
{
MessageBox(hWnd, TEXT("Button pushed"), TEXT("OK button"), MB_OK);
}
else if (id == IDCANCEL)
{
EndDialog(hWnd, id);
}
}
return 0;
}
int main()
{
std::cout << "Hello World!\n";
DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_DIALOG1), NULL, (DLGPROC)WndProc);
}
运行后如下:
按确定键弹出MessageBox;按取消键关闭整个对话框。
至此,一个界面开发入门算是介绍完了。不过代码都是抄的stack大佬的,我自己凭本事是入不了门的😂。C++入门太难了,网上干货少,api难找,找到了也不知道怎么用,vs2019又对新手不友好,总之太难了🤣。
比如这个对话框,如果只看官方文档的话,api解释如下:
void DialogBoxA(
[in, optional] hInstance,
[in] lpTemplate,
[in, optional] hWndParent,
[in, optional] lpDialogFunc
);
四个参数解释如下:
Parameters
[in, optional] hInstance
Type: HINSTANCE
A handle to the module which contains the dialog box template. If this parameter is NULL, then the current executable is used.
[in] lpTemplate
Type: LPCTSTR
The dialog box template. This parameter is either the pointer to a null-terminated character string that specifies the name of the dialog box template or an integer value that specifies the resource identifier of the dialog box template. If the parameter specifies a resource identifier, its high-order word must be zero and its low-order word must contain the identifier. You can use the MAKEINTRESOURCE macro to create this value.
[in, optional] hWndParent
Type: HWND
A handle to the window that owns the dialog box.
[in, optional] lpDialogFunc
Type: DLGPROC
A pointer to the dialog box procedure. For more information about the dialog box procedure, see DialogProc.
原文链接:
DialogBoxA macro (winuser.h) - Win32 apps | Microsoft Learn
文档里连个示例都没有,一个新手,光看这些,如何知道要怎么调用呢?更别提按钮点击事件了。到最后还是得去百度谷歌搜,搜到了合适的教程可以很快上手,但搜了半天都找不到合适的,那岂不是要难受死了?白白浪费了大把的时间。这也是本文的意义所在。