天天看點

Windows程式内部運作原理的一個示例

Windows程式内部運作原理的一個示例

一、原理

http://blog.163.com/zhoumhan_0351/blog/static/3995422720103401415721

二、例程

#include "windows.h"

#include "stdio.h"

LRESULT CALLBACK WinWeProc(

  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_ASTERISK);

wndcls.hInstance=hInstance;

wndcls.lpfnWndProc=WinWeProc;

wndcls.lpszClassName="WinWe2010";

wndcls.lpszMenuName=NULL;

wndcls.style=CS_HREDRAW | CS_VREDRAW;

RegisterClass(&wndcls);

HWND hwnd;

hwnd=CreateWindow("WinWe2010","I am Here",WS_OVERLAPPEDWINDOW,CW_USEDEFAULT,CW_USEDEFAULT,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 msg.wParam;

}

LRESULT CALLBACK WinWeProc(

  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 szChar[20];

 sprintf(szChar,"char code is %d",wParam);

 MessageBox(hwnd,szChar,"char",0);

 break;

case WM_LBUTTONDOWN:

 MessageBox(hwnd,"mouse","message",0);

 HDC hdc;

 hdc=GetDC(hwnd);

 TextOut(hdc,0,50,"MY home",strlen("MY home"));

 ReleaseDC(hwnd,hdc);

 break;

case WM_PAINT:

 HDC hDc;

 PAINTSTRUCT ps;

 hDc=BeginPaint(hwnd,&ps);

 TextOut(hDc,0,0,"HELLO",strlen("HELLO"));

 EndPaint(hwnd,&ps);

 break;

case WM_CLOSE:

 if(IDYES==MessageBox(hwnd,"Really?","message",MB_YESNO)){

 DestroyWindow(hwnd);

 }

 break;

case WM_DESTROY:

 PostQuitMessage(0);

 break;

default:

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

   }

return 0;

}

三、注意點

1、wndcls.hbrBackground=(HBRUSH)GetStockObject(BLACK_BRUSH);

2、char szChar[20];

 sprintf(szChar,"char code is %d",wParam);

 MessageBox(hwnd,szChar,"char",0);

3、hdc=GetDC(hwnd);

 TextOut(hdc,0,50,"MY home",strlen("MY home"));

 ReleaseDC(hwnd,hdc);

//記得GetDC後要ReleaseDC,否則可能記憶體洩露。在Windows平台下,所有的圖形操作操作都是選用DC的,可以把DC想成畫布,我們不是作畫者,而是指揮者,指揮DC畫什麼圖形。實際上,DC是一個包含裝置(實體裝置,如輸出裝置,顯示器,及裝置驅動程式等)資訊的結構體。DC也是一種資源。

4、hDc=BeginPaint(hwnd,&ps);

 TextOut(hDc,0,0,"HELLO",strlen("HELLO"));

 EndPaint(hwnd,&ps);

//BeginPaint後要EndPaint,他們是一對,隻能用在WM_PAINT消息響應代碼中使用。

5、調用UpdateWindow時,會發送WM_PAINT消息給視窗函數,對視窗函數進行重新整理。

6、邏輯表達式中,當是判斷相等時,如果有常量,應當把常量放前面,友善調試和糾錯,如下所示:

 if(IDYES==MessageBox(hwnd,"Really?","message",MB_YESNO))

7、變量的命名約定

Windows程式内部運作原理的一個示例