Delphi - ErrorCode查询

技术交流,DH.

我们一般在调用了一些API后都会用GetLastError来获得错误信息,但是信息都是Integer的,我们知道是什么意思么?
嘿嘿,是的,有msdn呀,当然还可以用FormatMessage函数来.
正好看了下Windows核心编程第一章有个例子,来用Delphi试一下.
主要用了FormatMessage函数,具体用法和注意事项就很多了,大家可以看MSDN了.

Unit UtMain;

Interface

Uses
  Windows,
  Messages,
  SysUtils,
  Variants,
  Classes,
  Graphics,
  Controls,
  Forms,
  Dialogs,
  CxGraphics,
  CxControls,
  CxLookAndFeels,
  CxLookAndFeelPainters,
  CxContainer,
  CxEdit,
  DxSkinsCore,
  DxSkinSeven,
  CxGroupBox,
  CxCheckBox,
  CxTextEdit,
  DxSkinsForm,
  CxLabel,
  Menus,
  CxMemo,
  StdCtrls,
  CxButtons;

Type
  TForm3 = Class(TForm)
    Cxlbl1: TcxLabel;
    DxSkinController1: TdxSkinController;
    CxtxtCode: TcxTextEdit;
    CxchkHex: TcxCheckBox;
    GrpDescription: TcxGroupBox;
    BtnSearch: TcxButton;
    CxmDescription: TcxMemo;
    Procedure BtnSearchClick(Sender: TObject);
    Procedure FormCreate(Sender: TObject);
  Private
    { Private declarations }

    DwCode: Cardinal;
    SystemLocale: Cardinal;
  Public
    { Public declarations }
  End;

Var
  Form3: TForm3;

Implementation

{$R *.dfm}

Procedure TForm3.BtnSearchClick(Sender: TObject);
Var
  B: Cardinal;
  HLib: Cardinal;
  Buf: PChar;
Begin
  If CxchkHex.Checked Then
    DwCode := StrToIntDef('$' + CxtxtCode.Text, 0)
  Else
    DwCode := StrToIntDef(CxtxtCode.Text, 0);
  GetMem(Buf, 256);
  Try
    // 尝试获取一下
    B := FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, Nil, DwCode, SystemLocale,
      Buf, 255, Nil);
    // 如果默认没有 查询下网络相关的
    If B = 0 Then
    Begin
      HLib := LoadLibraryEx('netmsg.dll', 0, DONT_RESOLVE_DLL_REFERENCES);
      Try
        Assert(HLib <> 0);
        B := FormatMessage(FORMAT_MESSAGE_FROM_HMODULE, Pointer(HLib), DwCode,
          SystemLocale, Buf, 255, Nil);
      Finally
        If HLib <> 0 Then
          FreeLibrary(HLib);
      End;
    End;
    If (B <> 0) Then
      CxmDescription.Text := Buf
    Else
      CxmDescription.Text := '没有找到错误码的相关描述';

  Finally
    FreeMem(Buf);
  End;
End;

Procedure TForm3.FormCreate(Sender: TObject);
Begin
  // 设置语言为默认
  SystemLocale := MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT)
End;

End.

我为了要dx的皮肤,所以这里用到了DevExpress控件,但是没有用到控件的其他功能,所以大家如果没有安装Dev,可以直接换成最普通的Button这些控件就可以了额.
来个图片看一下:
image

posted @ 2010-03-20 00:33  HuangJacky  阅读(1839)  评论(2编辑  收藏  举报
AdminLogin