首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

windows核心编程-异常处理

2012-11-22 
windows核心编程---错误处理如果我们自己写程序的时候检测到一个错误的时候,可能希望向用户显示错误的文本

windows核心编程---错误处理

        如果我们自己写程序的时候检测到一个错误的时候,可能希望向用户显示错误的文本表述,而不是一个干巴巴的错误代码windows提供了一个函数可以将错误代码转换成错误文本描述,这个函数是FormatMessage。

     TheFormatMessage function formats a message string. The function requires a message definition as input. The message definition can come from a buffer passed into the function. It can come from a message table resource in an already-loaded module. Or the caller can ask the function to search the system's message table resource(s) for the message definition. The function finds the message definition in a message table resource based on a message identifier and a language identifier. The function copies the formatted message text to an output buffer, processing any embedded insert sequences if requested.

#include <windows.h>#include "resource.h"LRESULT CALLBACK DialogProc(HWND ,UINT,WPARAM,LPARAM) ;void OnInitDialog(HWND hDlg);void OnOK(HWND hDlg);int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)       { MSG msg;HWND hwnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, (DLGPROC)DialogProc);       ShowWindow(hwnd, SW_SHOW);       UpdateWindow(hwnd);           while(GetMessage(&msg, NULL, 0, 0))       { if( !IsDialogMessage( hwnd, &msg ) ){TranslateMessage(&msg);DispatchMessage(&msg);  }}    return msg.wParam;    }LRESULT CALLBACK DialogProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam)       {  switch(uMsg)    {    case WM_INITDIALOG:  OnInitDialog(hWnd);SetWindowPos(hWnd,NULL,500,200,0,0,SWP_NOSIZE); return TRUE;           case WM_COMMAND:    if(LOWORD(wParam) == IDOK)     {                   OnOK(hWnd);               return TRUE;    }if(LOWORD(wParam) == IDCANCEL){PostQuitMessage(0);return TRUE;}break;            case WM_DESTROY:    PostQuitMessage(0);    break;    }    return FALSE;}void OnInitDialog(HWND hDlg){SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)LoadIcon(NULL, MAKEINTRESOURCE(IDI_ICON1)));SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)LoadIcon(NULL, MAKEINTRESOURCE(IDI_ICON1)));SetDlgItemInt(hDlg, IDC_ERRORCODE, 0, FALSE);}void OnOK(HWND hDlg){DWORD dwError = GetDlgItemInt(hDlg,IDC_ERRORCODE,NULL, FALSE);LPVOID lpMsgBuf;FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,NULL,dwError,MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language(PTSTR)&lpMsgBuf,  0,NULL );SetDlgItemText(hDlg,IDC_ERRORTEXT,(PCTSTR)lpMsgBuf);// Free the buffer.LocalFree(lpMsgBuf);}




热点排行