Win32编程系列文章:https://www.jianshu.com/nb/30332818
添加控件
在Hello World基础上,添加:
wWinMain
内部创建变量,使用的是如下的方法:1
2
3
4
5
6
7
8
9
10//创建静态文本控件
HWND hStatic = CreateWindow(
TEXT("static"), //静态文本框的类名
TEXT("hahaha"), //控件的文本
WS_CHILD /*子窗口*/ | WS_VISIBLE /*创建时显示*/ | WS_BORDER /*带边框*/,
120 /*X坐标*/, 20/*Y坐标*/, 150/*宽度*/, 80/*高度*/, hwnd/*父窗口句柄*/,
(HMENU)1, //为控件指定一个唯一标识符
hInstance, //当前实例句柄
NULL
);- 类似可以创建按钮、输入框等,如下:
1
2
3
4
5// 下面一行代码创建输入框
CreateWindow(L"EDIT", 0, WS_BORDER | WS_CHILD | WS_VISIBLE, 56, 10, 50, 18, hwnd, 0, hInstance, 0);
// 下面一行代码创建按钮
my_button = CreateWindow(L"BUTTON", L"一个按钮", WS_CHILD | WS_VISIBLE, 70, 70, 80, 25, hwnd, (HMENU)8, hInstance, 0); - 创建下拉框的时候会比较麻烦,需要绑定数据,如下所示:
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
33TCHAR Planets[9][10] =
{
TEXT("Mercury"), TEXT("Venus"), TEXT("Terra"), TEXT("Mars"),
TEXT("Jupiter"), TEXT("Saturn"), TEXT("Uranus"), TEXT("Neptune"),
TEXT("Pluto??")
};
int xpos = 100; // Horizontal position of the window.
int ypos = 100; // Vertical position of the window.
int nwidth = 200; // Width of the window
int nheight = 200; // Height of the window
HWND hwndParent = hwnd; // Handle to the parent window
HWND hWndComboBox = CreateWindow(L"COMBOBOX", TEXT(""),
CBS_DROPDOWN | CBS_HASSTRINGS | WS_CHILD | WS_OVERLAPPED | WS_VISIBLE,
xpos, ypos, nwidth, nheight, hwndParent, NULL, hInstance,
NULL);
TCHAR A[16];
int k = 0;
memset(&A, 0, sizeof(A));
for (k = 0; k <= 8; k += 1)
{
wcscpy_s(A, sizeof(A) / sizeof(TCHAR), (TCHAR*)Planets[k]);
// Add string to combobox.
SendMessage(hWndComboBox, (UINT)CB_ADDSTRING, (WPARAM)0, (LPARAM)A);
}
// Send the CB_SETCURSEL message to display an initial item
// in the selection field
SendMessage(hWndComboBox, CB_SETCURSEL, (WPARAM)2, (LPARAM)0);
绑定事件
- 在
WindowProc
里面添加对应的switch-case,如下: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
35wchar_t a[6] = TEXT("Dian0");
int wmId = LOWORD(wParam);
int wmEvent = HIWORD(wParam);
switch (uMsg)
{
case WM_CLOSE:
DestroyWindow(hwnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_COMMAND:
if (wmEvent == BN_CLICKED) {
a[4] = L'0' + (a[4] - L'0' + 1) % 10;
SetWindowText(my_button, a);
break;
}
else if (wmEvent == CBN_SELCHANGE)
// If the user makes a selection from the list:
// Send CB_GETCURSEL message to get the index of the selected list item.
// Send CB_GETLBTEXT message to get the item.
// Display the item in a messagebox.
{
int ItemIndex = SendMessage((HWND)lParam, (UINT)CB_GETCURSEL,
(WPARAM)0, (LPARAM)0);
TCHAR ListItem[256];
(TCHAR)SendMessage((HWND)lParam, (UINT)CB_GETLBTEXT,
(WPARAM)ItemIndex, (LPARAM)ListItem);
MessageBox(hwnd, (LPCWSTR)ListItem, TEXT("Item Selected"), MB_OK);
}
// Here don't write break on purpose!
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
// 还是得要去处理default的事件