windows下的错误代码处理

看了下《windows核心编程》的错误代码处理部分。我这才知道错误代码处理的重要性,以前的时候有错误就埋头苦调,现在发现当初好傻。埋头苦调根本就是又费力又费时,而且错误代码还不一定能调的出来。以后就用Windows下面的错误代码处理额···

下面是一个例子

#include 
DWORD GetLastErrorBox(HWND hWnd, LPSTR lpTitle);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

LPSTR szAppName = "Curves";
LPSTR szTitle = "Curves Application";

int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
MSG msg;
HWND hWnd;
WNDCLASS wc;

// 注册窗口类
wc.style = CS_OWNDC;
wc.lpfnWndProc = (WNDPROC)WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = NULL;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wc.lpszMenuName = NULL;
wc.lpszClassName = szAppName;

if (!RegisterClass(&wc))
{
GetLastErrorBox(NULL, "Error in RegisterClass");
return (FALSE);
}
// 创建窗口
hWnd = CreateWindow(
szAppName,
szTitle,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0,
NULL,
NULL,
hInstance,
NULL
);

if (!hWnd)
{
GetLastErrorBox(hWnd, "Error in CreateWindow");
return (FALSE);
}
// 显示更新
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
// 消息循环
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}

return (int)(msg.wParam);

UNREFERENCED_PARAMETER(lpCmdLine);
}

LRESULT CALLBACK WndProc(
HWND hWnd,
UINT message,
WPARAM uParam,
LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
{
SetWindowLong(hWnd,GWL_EXSTYLE,NULL);//SetWindowLong(NULL,GWL_EXSTYLE,NULL);

}
GetLastErrorBox(hWnd, "Error in WM_CREATE");
break;

case WM_DESTROY:

PostQuitMessage(0);
break;

default:
return (DefWindowProc(hWnd, message, uParam, lParam));
}
return (0);
}

// 显示错误信息
DWORD GetLastErrorBox(HWND hWnd, LPSTR lpTitle)
{
LPVOID lpv;
DWORD dwRv;

if (GetLastError() == 0) return 0;

dwRv = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError(),
MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
(LPSTR)&lpv,
0,
NULL);

MessageBox(hWnd, (LPCSTR)lpv, lpTitle, MB_OK);

if(dwRv)
LocalFree(lpv);

SetLastError(0);
return dwRv;
}

在WM_CREATE的时候若是我在函数SetWindowLong(hWnd,GWL_EXSTYLE,NULL);第一个参数传入NULL,此时其实窗口还没生成,又何来句柄,然后就会出现错误消息,

我们自己写个函数把错误代码转化成我们能看得懂的东西。运行上面修改后的程序,就会弹出错误的框,内容是"Invalid window Handle",这下就错误一目了然了额····

上面这个错误错里就当作模版处理,记在博客上面····

标签:SDK