您的位置:首页 > 其它

c创建win窗口

2015-07-08 02:34 281 查看
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 = 0;
wndclass.cbWndExtra = 0;
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 0;
}

hwnd = CreateWindow(szAppName,
TEXT("HELLO WORLD"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
640,
480,
NULL,
NULL,
hInstance,
NULL);
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 WIN8"), -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);
}


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

原因:调用了一个多媒体函数,而多媒体对象库并未包含在默认项目内
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: