刚开始学习DirectX,使用VS2013编译环境,建立第一个窗口,学习WinMain函数。
WinMain函数是windows应用程序的入口,相当于c语言的main函数。
WinMain函数主要实现以下功能:
1.注册窗口类,建立窗口,执行其他必要的初始化的操作;
2.进入消息循环,根据从应用程序消息队列接受的消息,调用相应的处理过程;
3.当消息循环检索到WM_QUIT消息时,终止程序运行。
首先建立win窗口空项目
添加c++文件,输入下面代码:
#include<windows.h>
#include<stdio.h>
LRESULT CALLBACK WndProc(
HWND hwnd, // handle to window
UINT uMsg, // message identifier
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
);
int WINAPI WinMain(
HINSTANCE hInstance, // handle to current instance
HINSTANCE hPrevInstance, // handle to previous instance
LPSTR lpCmdLine, // command line
int nCmdShow // show state
)
{
WNDCLASS wndclass;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hInstance = hInstance;
wndclass.lpfnWndProc = WndProc;
wndclass.lpszClassName = "我的窗口";
wndclass.lpszMenuName = NULL;
wndclass.style = CS_HREDRAW | CS_VREDRAW;
RegisterClass(&wndclass); //注册窗口类
HWND hwnd;
hwnd = CreateWindow("我的窗口", "窗口", WS_OVERLAPPEDWINDOW,
0, 0, 640, 480, NULL, NULL, hInstance, NULL);
ShowWindow(hwnd, SW_SHOWNORMAL);
UpdateWindow(hwnd);
MSG Msg;
while (GetMessage(&Msg, NULL, 0, 0))
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
return 0;
}
LRESULT CALLBACK WndProc(
HWND hwnd, // handle to window
UINT uMsg, // message identifier
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
)
{
switch (uMsg)
{
case WM_CHAR:
char strChar[20];
sprintf_s(strChar, "char is %d", wParam);
MessageBox(hwnd, strChar, "window", MB_OK);
break;
case WM_LBUTTONDOWN:
MessageBox(hwnd, "mouse left-click", "window", MB_OK);
HDC hdc;
hdc = GetDC(hwnd);
TextOut(hdc, 0, 50, "hello mouse left-click", strlen("hello mouse left-click"));
ReleaseDC(hwnd, hdc);
break;
case WM_RBUTTONUP:
MessageBox(hwnd, "release mouse", "window", MB_OK);
hdc = GetDC(hwnd);
TextOut(hdc, 0, 80, "hello release mouse", strlen("hello release mouse"));
ReleaseDC(hwnd, hdc);
break;
case WM_CLOSE:
PostQuitMessage(0);
break;
case WM_DESTROY:
DestroyWindow(hwnd);
break;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return 0;
}
编译报错 cannot convert from 'const char ' to 'LPCWSTR'
错误的原因是项目字符集设置为Unicode,可以将报错的地方字符(char)类型改为宽字符(wchar_t)类型,也可以更改字符集为 Multi-Byte 。
项目(Project)—> 属性(Property Pages)—> 配置属性(Configuration Properties)—> 常规(General)—>字符集(Character Set)
参考资料:点击打开链接