跳至主要内容

17.子窗口

子窗口控件

  • WINODWS提供了几个预定义的窗口类以方便我们的使用,我们一般就它们叫做子窗口控件,简称控件。
  • 空间会自己处理消息,并在自己状态发生时通知父窗口
  • 预定义的控件有
    • 按钮、复选框、编辑框、静态字符串标签和滚动条等
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include "framework.h"
#include "Win32.h"


#define IDC_EDIT_1 0x100
#define IDC_BUTTON_1 0x101
#define IDC_BUTTON_2 0x102

HINSTANCE g_hInstance;
LRESULT CALLBACK WindowsProc(
HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM rParam
) {
char szOutBuff[0x80];
wsprintfA(szOutBuff, "消息类型: %lx\n", uMsg);
OutputDebugStringA(szOutBuff);
switch (uMsg) {
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_CREATE:
CreateWindowA(
"EDIT",
"",
WS_CHILD | WS_VISIBLE | WS_VSCROLL | ES_MULTILINE,
0,
0,
500,
300,
hwnd,
(HMENU)IDC_EDIT_1,
g_hInstance,
NULL
);
CreateWindowA(
"BUTTON",
"设置",
WS_CHILD | WS_VISIBLE,
520,
180,
60,
30,
hwnd,
(HMENU)IDC_BUTTON_1,
g_hInstance,
NULL
);
CreateWindowA(
"BUTTON",
"获取",
WS_CHILD | WS_VISIBLE,
520,
220,
60,
30,
hwnd,
(HMENU)IDC_BUTTON_2,
g_hInstance,
NULL
);
break;
case WM_COMMAND:
switch (LOWORD(wParam)) {
case IDC_BUTTON_1:
SetDlgItemText(hwnd, IDC_EDIT_1, TEXT("测试"));
break;
case IDC_BUTTON_2:
GetDlgItemTextA(hwnd,IDC_EDIT_1,szOutBuff,100);
MessageBoxA(hwnd, szOutBuff, szOutBuff, 0);

break;
}
break;
}


return DefWindowProc(hwnd, uMsg,wParam,rParam);
}


int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{

g_hInstance = hInstance;
//DWORD dwAddr = (DWORD)hInstance;
char szOutBuff[80];

//1.定义你的窗口是怎么样的
WNDCLASS wndclass = { 0 };
TCHAR szAppName[] = TEXT("MyApp");
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.lpszClassName = szAppName;
wndclass.hInstance = hInstance;
wndclass.lpfnWndProc = WindowsProc;
RegisterClass(&wndclass);

//2.创建并显示窗口
HWND hwnd = CreateWindow(szAppName,TEXT("Hello"),WS_OVERLAPPEDWINDOW,10,10,600,300,NULL,NULL,hInstance,NULL);
if (hwnd == NULL) {
wsprintfA(szOutBuff, "Error: %d\n", GetLastError());
OutputDebugStringA(szOutBuff);
return 0;
}

ShowWindow(hwnd, SW_SHOW);

//3.接收并处理消息
MSG msg;
BOOL bRet;
while ((bRet = GetMessage(&msg, NULL, 0, 0)) != 0) {
if (bRet == -1)
{
wsprintfA(szOutBuff, "Error: %d\n", GetLastError());
OutputDebugStringA(szOutBuff);
}
else {
//转换消息
TranslateMessage(&msg);
//分发消息
DispatchMessageW(&msg);
}
}

return 0;
}

关于本文

由 GuQing 撰写,采用 CC BY-NC 4.0 许可协议。