c创建win窗口

时间:2024-05-09 00:06:13

windows程序设计示例:

 #include "windows.h"
#pragma comment(lib, "winmm") LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
static TCHAR szAppName[] = TEXT("HELLO WIN");
HWND hwnd;
MSG msg;
WNDCLASS wndclass; wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = ;
wndclass.cbWndExtra = ;
wndclass.hInstance = hInstance;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_HAND);
wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = szAppName; if (!RegisterClass(&wndclass))
{
MessageBox(NULL, TEXT("ERROR"), TEXT(szAppName), MB_ICONERROR);
return ;
} hwnd = CreateWindow(szAppName,
TEXT("HELLO WORLD"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
,
,
NULL,
NULL,
hInstance,
NULL);
ShowWindow(hwnd, iCmdShow);
UpdateWindow(hwnd); while (GetMessage(&msg,NULL,,))
{
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 ;
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
GetClientRect(hwnd, &rect);
DrawText(hdc, TEXT("HELLO WIN8"), -, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
EndPaint(hwnd, &ps);
return ;
case WM_DESTROY:
PostQuitMessage();
return ;
}
return DefWindowProc(hwnd, message, wparam, lparam);
}

创建步骤:

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

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