VisualBasic辅导:编程获得系统错误信息提示

2026-03-23
很多编程爱好者在VB的API编程中经常遇到API调用中的错误代码(Error Code,在API调用中遇到错误时使用GetLastError函数可以得到)。但是很多的时候错误代码并没有多大用处,因为你并不知道代码所代表的含义。而实际上,在Windows中为每个错误码提供了一个错误提示,而且适应不同的语言版本(既如果你使用中文版Windows,提示也是中文的)。只要通过API编程就可以获得详细的错误提示。
   下面通过程序来介绍,运行下面的程序,首先要在Form中加入一个ListBox和CommandButton在将下面的代码加入到form的代码窗口中。
   Private Declare Function FormatMessage Lib 'kernel32' _
   Alias 'FormatMessageA' (ByVal dwFlags As Long, _
   lpSource As Any, ByVal dwMessageId As Long, _
   ByVal dwLanguageId As Long, ByVal lpBuffer _
   As String, ByVal nSize As Long, Arguments As _
   Long) As Long
   Private Declare Function GetLastError Lib 'kernel32' _
   () As Long
   Private Declare Function CloseHandle Lib 'kernel32' _
   (ByVal hObject As Long) As Long
   Const FORMAT_MESSAGE_FROM_SYSTEM = &H1000
   Const FORMAT_MESSAGE_IGNORE_INSERTS = &H200
   Private Sub Command1_Click()
   Dim ErrID As Long
   Dim astr As String
   Dim bstr As String
   Dim l As Long
   astr = String$(256, 20)
   '获得具体的错误信息
   For ErrID = 0 To 8191
   l = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM Or _
   FORMAT_MESSAGE_IGNORE_INSERTS, 0&, ErrID, 0&, _
   astr, Len(astr), ByVal 0)
   If l Then
   bstr = Left$(astr, InStr(astr, Chr(10)) - 2)
   '将错误信息加入列表框
   List1.AddItem Str(ErrID) + ' ' + bstr
   End If
   Next ErrID
   End Sub
   运行程序,点击Command1,错误代码和向对应的错误提示信息就全部列在ListBox中了。以上程序在Win95,VB5.0下运行通过。