Windows API程序入门学习(1)
学习目的
- 了解 windows操作系统应用程序开发的基本概念,win32 API函数、消息与事件驱动;
- 掌握WinMain函数的基本框架,窗口定义、窗口创建、消息循环及窗口过程函数;
作业要求
动手写第一个基于windows API 的基于窗体、消息循环、事件驱动的 Windows C语言风格的Windows 程序。
实现步骤
- WinMain函数的定义
- 创建一个窗口
- 进行消息循环
- 编写窗口过程函数
参考书籍
《Windows程序设计》(charle petzold著)
《深入浅出MFC》(侯俊杰著)
《VC++深入讲解》(孙鑫编著)
实现代码
#include <windows.h>
#include <stdio.h>
LRESULT CALLBACK WinSunProc(
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 wndcls;
wndcls.cbClsExtra=0;
wndcls.cbWndExtra=0;
wndcls.hbrBackground=(HBRUSH)GetStockObject(BLACK_BRUSH);
wndcls.hCursor=LoadCursor(NULL,IDC_CROSS);
wndcls.hIcon=LoadIcon(NULL,IDI_ERROR);
wndcls.hInstance=hInstance;
wndcls.lpfnWndProc=WinSunProc;
wndcls.lpszClassName="App1"; //窗口标题
wndcls.lpszMenuName=NULL;
wndcls.style=CS_HREDRAW | CS_VREDRAW;
RegisterClass(&wndcls); //窗口注册
HWND hwnd;
hwnd=CreateWindow("App1","我的第一个程序框体",WS_OVERLAPPEDWINDOW,
0,0,600,400,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 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,"消息框",0);
break;
case WM_LBUTTONDOWN: //鼠标左键点击
MessageBox(hwnd,"鼠标点击了一次","消息框",0);
HDC hdc;
hdc=GetDC(hwnd);
TextOut(hdc,0,50,"hellow world!",strlen("hellow world!"));
ReleaseDC(hwnd,hdc);
break;
case WM_PAINT:
HDC hDC;
PAINTSTRUCT ps;
hDC=BeginPaint(hwnd,&ps);
{
SetTextColor(ps.hdc, RGB(220, 15, 200));
TextOut(hDC,0,0,"一个简单的win32程序",strlen("一个简单的win32程序"));
}
EndPaint(hwnd,&ps); //释放环境变量句柄
break;
case WM_CLOSE: //关闭窗口时响应
if(IDYES==MessageBox(hwnd,"是否真的结束?","weixin",MB_YESNO))
{
DestroyWindow(hwnd);
}
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd,uMsg,wParam,lParam);
}
return 0;
}
运行结果
调试成功,开始运行
鼠标单击界面会有消息框弹出
点击
确定
键,消息框关闭,并出现"hellow world!"
点击
关闭
按键弹出提示框确认是否退出