曾经在Win32平台下奋战的程序员们想必记得,为了弄清楚“消息循环”的概念,度过多少不眠之夜。尽管如今在应用程序代码的编写过程中,我们已经不再需要它,但是深刻理解Windows平台内部的消息流转机制依然必要..
在早年直接用Win32/Win16 API写程序的时代,消息循环是我们必须搞懂的第一个观念。现在,不管你用是Windows上面的哪一套Application Framework(MFC、VCL、VB、.NET Framework),甚至Unix、Linux、MacOSX上面的Application Framework,都不太容易看到消息循环。事实上,消息循环依然存在,只是被这些ApplicationFramework包装起来,深深地埋藏在某个角落。
本文章试图唤起大家对于消息循环的回忆,也试图解释消息循环如何被封装进.NET Framework的Windows Forms中。虽然Windows Forms将这一切都藏起来,但是也留下许多空间,让我们可以自行处理Win32的消息。
传统的Windows 程序
传统的Windows程序,只利用Win32 API撰写,下面是一个程序范例,为了节省篇幅,我将其中许多程序代码省略:
// 程序进入点
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow){
MSG msg;
if (!InitInstance (hInstance, nCmdShow)){
return FALSE;
}
// 主消息循环:
while (GetMessage(&msg, NULL, 0, 0)){
TranslateMessage(&msg); DispatchMessage(&msg);
}
return (int) msg.wParam;
}
// 函数: WndProc(HWND, unsigned, WORD, LONG)
// 用途: 处理主窗口的消息。
LRESULT CALLBACK WndProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
int wmId, wmEvent; PAINTSTRUCT ps;
HDC hdc;
switch (message){
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// 剖析菜单选取项目:
switch (wmId){
case IDM_ABOUT:
DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX,hWnd, (DLGPROC)About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message,wParam,lParam);
}
break;
case WM_PA
在早年直接用Win32/Win16 API写程序的时代,消息循环是我们必须搞懂的第一个观念。现在,不管你用是Windows上面的哪一套Application Framework(MFC、VCL、VB、.NET Framework),甚至Unix、Linux、MacOSX上面的Application Framework,都不太容易看到消息循环。事实上,消息循环依然存在,只是被这些ApplicationFramework包装起来,深深地埋藏在某个角落。
本文章试图唤起大家对于消息循环的回忆,也试图解释消息循环如何被封装进.NET Framework的Windows Forms中。虽然Windows Forms将这一切都藏起来,但是也留下许多空间,让我们可以自行处理Win32的消息。
传统的Windows 程序
传统的Windows程序,只利用Win32 API撰写,下面是一个程序范例,为了节省篇幅,我将其中许多程序代码省略:
// 程序进入点
int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPTSTR lpCmdLine, int nCmdShow){
MSG msg;
if (!InitInstance (hInstance, nCmdShow)){
return FALSE;
}
// 主消息循环:
while (GetMessage(&msg, NULL, 0, 0)){
TranslateMessage(&msg); DispatchMessage(&msg);
}
return (int) msg.wParam;
}
// 函数: WndProc(HWND, unsigned, WORD, LONG)
// 用途: 处理主窗口的消息。
LRESULT CALLBACK WndProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
int wmId, wmEvent; PAINTSTRUCT ps;
HDC hdc;
switch (message){
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// 剖析菜单选取项目:
switch (wmId){
case IDM_ABOUT:
DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX,hWnd, (DLGPROC)About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message,wParam,lParam);
}
break;
case WM_PA
| 对此文章发表了评论 |

