An easy way to get error descriptions from Windows API error numbers

May 29, 2010 — Leave a comment

Perhaps this is common knowledge for a lot of people but even though I have been working with Windows APIs from VB.NET quite a lot recently, I did not know about this little ‘trick’ until today.

When I am working with a Windows API function from .NET I usually look up what the common return values are for that function that indicate an error has occurred, so that I can test the result of the API call to see if one of these error numbers was returned and show an appropriate message to the user. This means having to define all of these error codes as constants and then having a big IF statement that tests the result of the API call to see which error code was returned and then displays a relevant error message, which needless to say is a bit of a boring and repetitive task.

That is now a thing of the past though because today I discovered the System.ComponentModel.Win32Exception class! Now all I have to do is check to see if the API call returned the success value (usually 0 but varies with different Windows APIs) and if it did not then I just create a new instance of Win32Exception and pass in the error number that the API returned. Now I can use the Message property of this new Win32Exception instance to get the error message for the error 🙂

For example:

If Not Result = NO_ERROR Then
MessageBox.Show(New System.ComponentModel.Win32Exception(Result).Message)
End If

Hope that helps someone else save a bit of time and effort as well.

No Comments

Be the first to start the conversation!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s