为了使Windows SDK程序结构更为清晰,可利用C 函数把程序模块化的特定,对Windows程序进行封装。
例如,用C语言编写在鼠标左键按下时,可在窗口的用户区显示一个字符串“Hello World!”的Windows程序。
打开VC6.0,选择【File】-->Project-->Win32 Application,工程名为:fen2,
选择【File】--》C++ Source File--》命名为: op.c,代码如下:
//op.c
#include <windows.h>
#include <stdio.h>
//定义全局变量
HINSTANCE hInst;
HWND hWnd;
MSG msg;
char lpszClassName[]="窗口";
char *ShowText;
//定义函数
ATOM MyRegisterClass(HINSTANCE hInstance);//注册窗口类函数
BOOL Create(HINSTANCE,int); //程序实例初始化函数
int Run(); //消息循环函数
LRESULT CALLBACK WndProc(HWND,UINT,
WPARAM,LPARAM);//窗口函数
//主函数
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
MyRegisterClass(hInstance); //定义和注册窗口类
Create(hInstance,nCmdShow); //创建窗口
ShowWindow(hWnd,nCmdShow); //显示窗口
UpdateWindow(hWnd); //更新屏幕显示
return Run(); //消息循环
}
//注册窗口类的函数
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASS wc;
wc.style=0;
wc.lpfnWndProc=WndProc;
wc.cbClsExtra=0;
wc.cbWndExtra=0;
wc.hInstance=hInstance;
wc.hIcon=LoadIcon(NULL,IDI_APPLICATION);
wc.hCursor=LoadCursor(NULL,IDC_ARROW);
wc.hbrBackground=(HBRUSH)GetStockObject(WHITE_BRUSH);
wc.lpszMenuName=NULL;
wc.lpszClassName=lpszClassName;
return RegisterClass(&wc);
}
//创建窗口的函数
BOOL Create(HINSTANCE hInstance,int nCmdShow)
{
hWnd=CreateWindow(lpszClassName,
"Windows",
WS_OVERLAPPEDWINDOW,
120,50,800,600,
NULL,
NULL,
hInstance,
NULL);
return TRUE;
}
//消息循环的函数
int Run()
{
while(GetMessage(&msg,NULL,0,0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
//窗口函数
LRESULT CALLBACK WndProc(HWND hWnd,UINT message, WPARAM wParam,LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
switch(message)
{
case WM_LBUTTONDOWN:
ShowText="Hello World!";
InvalidateRect(hWnd,NULL,1);
break;
case WM_PAINT:
hdc=BeginPaint(hWnd,&ps);
TextOut(hdc,50,50,ShowText,strlen("Hello World!"));
EndPaint(hWnd,&ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd,message,wParam,lParam);
}
return 0;
}
效果如下: