Check result of call into Windows API

  • Thread starter Thread starter Lee
  • Start date Start date
L

Lee

Using Windows XP with all updates applied and Visual Studio 2.0.

I am trying to develop some common error-handling of Windows API
invocations that fail and am using MessageBeep as the API to test with.

Given 1) the following Imports statement:

Imports System.Runtime.InteropServices

2) the following declaration of MessageBeep:

<DllImport("user32.dll", _
EntryPoint:="MessageBeep", _
SetLastError:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Public Function MessageBeep(ByVal wType As Int32) As Boolean
End Function

3) the following code to test passing an invalid value to MessageBeep

Dim MBResult As Boolean
Dim MBErrorCode As Integer

MBResult = MessageBeep(-2)

If MBResult Then
MBErrorCode = Marshal.GetLastWin32Error
End If

When I set a break-point after the assignment to MBErrorCode, I see
that it has a value of 127 -- "The specified procedure could not be
found". I was expecting a value of 87 -- "The parameter is incorrect".

Note that when I pass MessageBeep a value of 0 -- a presumably valid
value -- I get the same result.
 
Try user32 instead of user32.dll in your dllimport (it should work like a
charm).
<DllImport("user32", _
EntryPoint:="MessageBeep", _
SetLastError:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Public Function MessageBeep(ByVal wType As Int32) As Boolean
End Function

Also you might want to take a look at this
http://www.codeproject.com/vb/net/apiexception.asp as it seems to be
discussing exactly what you are trying to do.

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
 
Greg:

Thanks for the response.

I found the answer(s) I needed in the .VB newsgroup...

It looks like MessageBeep will always succeed -- or at least not fail
for an invalid parameter.

I modified my test to use GetTempFileName specifying an invalid path
and the error detection worked just as it should.
 
Back
Top