c创建win窗口

windows程序设计示例:

 1 #include "windows.h"
 2 #pragma comment(lib, "winmm")
 3 
 4 LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
 5 
 6 int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
 7 {
 8     static TCHAR szAppName[] = TEXT("HELLO WIN");
 9     HWND hwnd;
10     MSG msg;
11     WNDCLASS wndclass;
12 
13     wndclass.style = CS_HREDRAW | CS_VREDRAW;
14     wndclass.lpfnWndProc = WndProc;
15     wndclass.cbClsExtra = 0;
16     wndclass.cbWndExtra = 0;
17     wndclass.hInstance = hInstance;
18     wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
19     wndclass.hCursor = LoadCursor(NULL, IDC_HAND);
20     wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
21     wndclass.lpszMenuName = NULL;
22     wndclass.lpszClassName = szAppName;
23 
24     if (!RegisterClass(&wndclass))
25     {
26         MessageBox(NULL, TEXT("ERROR"), TEXT(szAppName), MB_ICONERROR);
27         return 0;
28     }
29 
30     hwnd = CreateWindow(szAppName,
31         TEXT("HELLO WORLD"),
32         WS_OVERLAPPEDWINDOW,
33         CW_USEDEFAULT,
34         CW_USEDEFAULT,
35         640,
36         480,
37         NULL,
38         NULL,
39         hInstance,
40         NULL);
41     ShowWindow(hwnd, iCmdShow);
42     UpdateWindow(hwnd);
43 
44     while (GetMessage(&msg,NULL,0,0))
45     {
46         TranslateMessage(&msg);
47         DispatchMessage(&msg);
48     }
49 
50     return msg.wParam;
51 }
52 
53 LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam)
54 {
55     HDC hdc;
56     PAINTSTRUCT ps;
57     RECT rect;
58 
59     switch (message)
60     {
61     case WM_CREATE:
62         PlaySound(TEXT("hellowin.wav"), NULL, SND_FILENAME | SND_ASYNC);
63         return 0;
64     case WM_PAINT:
65         hdc = BeginPaint(hwnd, &ps);
66         GetClientRect(hwnd, &rect);
67         DrawText(hdc, TEXT("HELLO WIN8"), -1, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
68         EndPaint(hwnd, &ps);
69         return 0;
70     case WM_DESTROY:
71         PostQuitMessage(0);
72         return 0;
73     }
74     return DefWindowProc(hwnd, message, wparam, lparam);
75 }
View Code

创建步骤:

1.创建一个WNDCLASS结构体

2.使用RegisterClass注册结构体

3.调用CreateWindow创建窗体并将句柄赋值给一个HWND结构体

4.调用ShowWindow显示窗体

5.调用UpdateWindow更新窗体

6.执行消息循环,使用GetMessage获取消息,使用TranslateMessage转换消息,使用DispatchMessage分发消息

 

PS:

如果不加#pragma comment(lib, "winmm"),会报错

错误 1 error LNK2019: 无法解析的外部符号 __imp__PlaySoundA@12,该符号在函数 _WndProc@16 中被引用 E:\Project\CWin\CWin\main.obj CWin

 

另外一种解决方法,项目-属性-链接器-输入-附加依赖项中添加winmm.lib

 

原因:调用了一个多媒体函数,而多媒体对象库并未包含在默认项目内

posted @ 2015-07-08 02:34  朋克  阅读(351)  评论(0编辑  收藏  举报