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 🙂
Hope that helps someone else save a bit of time and effort as well.