FormatMessage获取错误代码描述

大家都知道获取错误代码用GetLastError,但是它返回的是错误标识,不是描述,我们可以用FormatMessage将其转换为本地语言的错误描述。FormatMessage的具体解释可以查看API的帮助。

 

Delphi代码

unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; Edit1: TEdit; Label1: TLabel; Memo1: TMemo; procedure Button1Click(Sender: TObject); private { Private declarations } procedure ShowErrorMsg(errcode:DWORD); public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin ShowErrorMsg(StrToInt64(Edit1.Text)); end; procedure TForm1.ShowErrorMsg(errcode:DWORD); var msg: array [0..256] of char; begin //清0 ZeroMemory(@msg, 256); FormatMessage( //FORMAT_MESSAGE_FROM_SYSTEM表示希望获得一个与系统定义的错误代码相对应的错误描述 //FORMAT_MESSAGE_IGNORE_INSERTS允许获得有%占位符的消息 FORMAT_MESSAGE_FROM_SYSTEM or FORMAT_MESSAGE_IGNORE_INSERTS, nil, errcode, //0,代表用本地缺省语言显示描述 0, msg, //缓冲区长度 256, nil ); Memo1.Text := string(msg); end; end.

 

C++(控制台)代码

#include <iostream> #include <windows.h> int main(int argc, char *argv[]) { int len = 256; CHAR* pmsg = (CHAR*)malloc(len*sizeof(CHAR)); DWORD errcode=0; //接收错误代码 printf("%s","请输入错误代码:"); scanf("%d",&errcode); FormatMessageA( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errcode, //获得缺省语言 MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT), pmsg, len, NULL); printf("错误描述:%s",pmsg); return 0; }

 

运行图片

你可能感兴趣的:(null,System,语言,button,Delphi,Forms)