下面是全部的代码:
有兴趣的朋友复制运行一下,看看结果。
#include <stdio.h>
#include <windows.h>
LRESULT CALLBACK WinSunPROC(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_CHAR:
//字符事件
{
char szChar[20];
sprintf(szChar, "char is %d", wParam);
MessageBox(hwnd, szChar, "hh", 0);
}break;
case WM_NCLBUTTONDOWN:
//鼠标左键按下事件
{
MessageBox(hwnd, "mouse clicked", "hh", 0);
HDC hdc;
hdc = GetDC(hwnd);
TextOut(hdc, 0, 50, "鼠标左键", strlen("鼠标左键"));
ReleaseDC(hwnd, hdc);
}break;
case WM_PAINT:
//窗口重绘事件
{
HDC hDc;
PAINTSTRUCT ps;
hDc = BeginPaint(hwnd, &ps);
TextOut(hDc, 0, 0, "第一课", strlen("第一课"));
EndPaint(hwnd, &ps);
}break;
case WM_CLOSE:
//窗口关闭事件
{
if (IDYES == MessageBox(hwnd, "是否真的结束?", "hh", MB_YESNO))
{
DestroyWindow(hwnd);
//销毁该窗口
}
}break;
case WM_DESTROY:
//窗口销毁事件
{
PostQuitMessage(0);
//往本线程的消息队列中发送一个。。。
}break;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(
HINSTANCE
hInstance,
HINSTANCE
hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow
)
{
WNDCLASS wndcls;
wndcls.cbClsExtra
= 0;
wndcls.cbClsExtra
= 0;
wndcls.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
wndcls.hCursor
= LoadCursor(NULL,IDC_CROSS);
wndcls.hIcon
= LoadIcon(NULL,IDI_APPLICATION);
wndcls.hInstance
= hInstance;
wndcls.lpfnWndProc
= WinSunPROC;
wndcls.lpszClassName = "xu";
wndcls.lpszMenuName
= NULL;
wndcls.style
= CS_HREDRAW | CS_VREDRAW;
if (RegisterClass(&wndcls) == 0)
{
DWORD dw = GetLastError();
//87:参数无效
MessageBox(NULL, TEXT("窗口类注册失败!"), TEXT("提示"), MB_OK);
return 1;
}
HWND hwnd;
hwnd = CreateWindow("xu", "测试", WS_OVERLAPPEDWINDOW, 10, 10, 600, 400, NULL, NULL, hInstance,NULL);
if (hwnd)
{
ShowWindow(hwnd, SW_SHOWNORMAL);
}
else
{
DWORD dw = GetLastError();
//1407 :找不到窗口类别。
MessageBox(NULL, TEXT("创建窗口失败!"), TEXT("提示"), MB_OK);
UnregisterClass("xu", hInstance);
//移除注册
return 1;
}
MSG msg;
while (GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}