跳至主要内容

15.第一个Windows程序

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
#include "framework.h"
#include "Win32.h"



LRESULT CALLBACK WindowsProc(
HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM rParam
) {
return DefWindowProc(hwnd, uMsg,wParam,rParam);
}


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

//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 许可协议。