Programming Windows 笔记:Windows and Messages (三)

本文为《Programming Windows, Fifth Edition》(Charles Petzold 著)第3章 “Windows and Messages” 的学习笔记总结。


HELLOWIN程序

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
#include <windows.h>
LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ;
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
static TCHAR szAppName[] = TEXT ("HelloWin") ;
HWND hwnd;
MSG msg ;
WNDCLASS wndclass ;
wndclass.style = CS_HREDRAW | CS_VREDRAW ;
wndclass.lpfnWndProc = WndProc ;
wndclass.cbClsExtra = 0 ;
wndclass.cbWndExtra = 0 ;
wndclass.hInstance = hInstance ;
wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION) ;
wndclass.hCursor = LoadCursor (NULL, IDC_ARROW) ;
wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
wndclass.lpszMenuName = NULL ;
wndclass.lpszClassName = szAppName ;
if (!RegisterClass (&wndclass))
{
MessageBox (NULL, TEXT ("This program requires Windows NT!"),
szAppName, MB_ICONERROR) ;
return 0 ;
}
hwnd = CreateWindow (szAppName, // window class name
TEXT ("The Hello Program"), // window caption
WS_OVERLAPPEDWINDOW, // window style
CW_USEDEFAULT, // initial x position
CW_USEDEFAULT, // initial y position
CW_USEDEFAULT, // initial x size
CW_USEDEFAULT, // initial y size
NULL, // parent window handle
NULL, // window menu handle
hInstance, // program instance handle
NULL) ; // creation parameters
ShowWindow (hwnd, iCmdShow) ;
UpdateWindow (hwnd) ;
while (GetMessage (&msg, NULL, 0, 0))
{
TranslateMessage (&msg) ;
DispatchMessage (&msg) ;
}
return msg.wParam ;
}
LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc ;
PAINTSTRUCT ps ;
RECT rect ;
switch (message)
{
case WM_CREATE:
PlaySound (TEXT ("hellowin.wav"), NULL, SND_FILENAME | SND_ASYNC) ;
return 0 ;
case WM_PAINT:
hdc = BeginPaint (hwnd, &ps) ;
GetClientRect (hwnd, &rect) ;
DrawText (hdc, TEXT ("Hello, Windows 98!"), -1, &rect,
DT_SINGLELINE | DT_CENTER | DT_VCENTER) ;
EndPaint (hwnd, &ps) ;
return 0 ;
case WM_DESTROY:
PostQuitMessage (0) ;
return 0 ;
}
return DefWindowProc (hwnd, message, wParam, lParam) ;
}

匈牙利标记法

许多 Windows 程序员都使用“匈牙利标记法”作为变量命名约定。这是为了纪念具有传奇色彩的微软程序员 Charles Simonyi。 这种标记法非常简单,即变量名以表明该变量数据类型的小写字母开始

当命名结构变量时,可使用结构名(或结构名称的缩写)的小写形式作为变量名称的前缀或整个变量名。例如,在 HELLOWIN 的 WinMain 函数中, msg 变量是一个 MSG 类型的结构, wndclass 是一个 WNDCLASS 类型的结构。在 WndProc 函数中, ps 是一个 PAINTSTRUCT 结构,而 rect 是一个 RECT 结构。

常用变量名前缀如下表所示。

前缀 数据类型
c char 或 WCHAR 或 TCHAR
by BYTE(无符号字符)
n short(短整型)
i int(整型)
x, y int,表示 x 坐标和 y 坐标
cx, cy int,表示 x 或 y 的长度,c 表示“count”(计数)
B 或 f BOOL(int); f 表示“flag”
w WORD(无符号短整型)
l LONG(长整型)
dw DWORD(无符号长整型)
fn 函数
s 字符串
sz 以零结束的字符串
h 句柄
p 指针