Windows API编程机理及简单范例

来源:互联网 发布:淘宝助理5.6.9.0下载 编辑:程序博客网 时间:2024/06/05 07:07
 

Windows程序的运作本质:以消息为基础,由事件驱动之(Message based,event driven)

Windows程序的进行依靠外部发生的事件来驱动。换句话说,程序不断等待(利用一个while回路),等待任何可能的输入,然后做判断,然后再做适当的处理。其中各种“输入”是由操作系统捕捉到之后以消息(一种数据结构)的形式通知程序。

接受并处理消息的主角就是窗口。每一个窗口都应该有一个函数负责处理消息,程序员必须负责设计这个所谓的“窗口函数”(window procedure,或称为window function)。如果窗口获得一个消息,这个窗口函数必须判断消息的类别,决定处理的方式。

Win32程序开发流程

Windows程序分为“程序代码”和“UI(User Interface)资源”两大部分,两部分最后以RC编译器整合为一个完整的EXE文件。

Windows程序运行机理图示

一个简单的范例

//-------------------------------------------------------------------

//win32 application test

//by ewook

//2008-3-14

//win32.cpp

//-------------------------------------------------------------------

#include <windows.h>

BOOL InitApplication(HINSTANCE hInstance);

BOOL InitInstance(HINSTANCE hInstance,int nCmdShow);

LRESULT CALLBACK Win32Proc(

HWND hwnd,

UINT uMsg,

WPARAM wParam,

LPARAM lParam

);

int WINAPI WinMain(

HINSTANCE hInstance,

HINSTANCE hPrevInstance,

LPSTR lpCmdLine,

int nCmdShow

) {

       MSG msg;

       if (!InitApplication(hInstance))

              return false;

       if (!InitInstance(hInstance,nCmdShow))

              return false;

       while (GetMessage(&msg,NULL,0,0)) {

              TranslateMessage(&msg);

              DispatchMessage(&msg);

       }

       return msg.wParam;

}

BOOL InitApplication(HINSTANCE hInstance) {

       WNDCLASS wc;

       wc.style=CS_HREDRAW | CS_VREDRAW;

       wc.lpfnWndProc=Win32Proc;

       wc.cbClsExtra=0;

       wc.cbWndExtra=0;

       wc.hInstance=hInstance;

       wc.hIcon=LoadIcon(NULL,IDI_APPLICATION);

       wc.hCursor=LoadCursor(NULL,IDC_ARROW);

       wc.lpszClassName="win32";

       wc.lpszMenuName=NULL;

       wc.hbrBackground=(HBRUSH)GetStockObject(DKGRAY_BRUSH);

       return RegisterClass(&wc);

}

BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) {

       HWND wnd;

       wnd=CreateWindow("win32","一个简单的win32程序",WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,NULL,NULL,hInstance,NULL);

       if(!wnd) return false;

       ShowWindow(wnd,SW_SHOWDEFAULT);

       UpdateWindow(wnd);

       return true;

}

LRESULT CALLBACK Win32Proc(

HWND hwnd,

UINT uMsg,

WPARAM wParam,

LPARAM lParam

) {

       switch(uMsg) {

       case WM_CLOSE:

              if(IDYES==MessageBox(hwnd,"确定退出程序?","提示",MB_YESNO))

                     DestroyWindow(hwnd);

              break;

       case WM_DESTROY:

              PostQuitMessage(0);

              break;

       default:

              return DefWindowProc(hwnd,uMsg,wParam,lParam);

             

       }

       return 0;

}

运行结果: