473,396 Members | 1,749 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Check result of call into Windows API

Lee
(I also posted this query in Microsoft.Public.DotNet.Framework
yesterday, but since I have received no responses, I am posting it here
too.)

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.

--
// Lee Silver
// Information Concepts Inc.
//
// Converting data into information since 1981

Jul 29 '06 #1
5 1619

Lee wrote:
(I also posted this query in Microsoft.Public.DotNet.Framework
yesterday, but since I have received no responses, I am posting it here
too.)

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.
Lee - MessageBeep is probably not a good choice for this. From the
remarks section of the MSDN help:

If it cannot play the specified alert sound, MessageBeep attempts to
play the system default sound.
What that means is that this function won't really fail for an invalid
value - it will simply play the system default sound. And that is what
it does on my system, it plays the sound even with an invalid value and
the function returns true.

--
Tom Shelton [MVP]

Jul 30 '06 #2
Lee
Tom:

Thanks for the feed-back.

I guess I mis-interpreted the docs and thought that an invalid value
would cause MessageBeep to fail.

I'll try a different API function and post my results here.

--
// Lee Silver
// Information Concepts Inc.
//
// Converting Data into Information since 1981
Tom Shelton wrote:
Lee wrote:
(I also posted this query in Microsoft.Public.DotNet.Framework
yesterday, but since I have received no responses, I am posting it here
too.)

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.

Lee - MessageBeep is probably not a good choice for this. From the
remarks section of the MSDN help:

If it cannot play the specified alert sound, MessageBeep attempts to
play the system default sound.

What that means is that this function won't really fail for an invalid
value - it will simply play the system default sound. And that is what
it does on my system, it plays the sound even with an invalid value and
the function returns true.

--
Tom Shelton [MVP]
Jul 30 '06 #3
Lee
Per Tom's suggestion I changed my test to use the GetTempFileName and
got the same result. My changes were as follows:

1)

<DllImport("kernel32.dll", _
EntryPoint:="GetTempFileNameA", _
CharSet:=CharSet.Ansi, _
ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)_
Public Function GetTempFileName(ByVal Path As String, _
ByVal PrefixString As String, _
ByVal Unique As Integer, _
ByVal TempFileName As
Text.StringBuilder) As Integer
End Function

and 2)

Dim GTFName As New Text.StringBuilder(255)
Dim GTFResult As Integer
Dim GTFErrorCode As Integer

GTFResult = GetTempFileName("x:\temp" & Chr(0), _
"zzzz" & Chr(0), _
0, _
GTFName)
If GTFResult = 0 Then
GTFErrorCode = Marshal.GetLastWin32Error
End If
GTFResult is 0 (failure) after the call to GetTempFileName, and
GTFErrorCode is 127. Note that I am forcing an error because "x:\temp"
does not exist (I have no X drive), but the error-code seems to be
wrong.

--
// Lee Silver
// Information Concepts Inc.
//
// Converting Data into Information since 1981

Lee wrote:
Tom:

Thanks for the feed-back.

I guess I mis-interpreted the docs and thought that an invalid value
would cause MessageBeep to fail.

I'll try a different API function and post my results here.

--
// Lee Silver
// Information Concepts Inc.
//
// Converting Data into Information since 1981
Tom Shelton wrote:
Lee wrote:
(I also posted this query in Microsoft.Public.DotNet.Framework
yesterday, but since I have received no responses, I am posting it here
too.)
>
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.
Lee - MessageBeep is probably not a good choice for this. From the
remarks section of the MSDN help:

If it cannot play the specified alert sound, MessageBeep attempts to
play the system default sound.
What that means is that this function won't really fail for an invalid
value - it will simply play the system default sound. And that is what
it does on my system, it plays the sound even with an invalid value and
the function returns true.

--
Tom Shelton [MVP]
Jul 30 '06 #4

Lee wrote:
Per Tom's suggestion I changed my test to use the GetTempFileName and
got the same result. My changes were as follows:

1)

<DllImport("kernel32.dll", _
EntryPoint:="GetTempFileNameA", _
CharSet:=CharSet.Ansi, _
ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)_
Public Function GetTempFileName(ByVal Path As String, _
ByVal PrefixString As String, _
ByVal Unique As Integer, _
ByVal TempFileName As
Text.StringBuilder) As Integer
End Function

and 2)

Dim GTFName As New Text.StringBuilder(255)
Dim GTFResult As Integer
Dim GTFErrorCode As Integer

GTFResult = GetTempFileName("x:\temp" & Chr(0), _
"zzzz" & Chr(0), _
0, _
GTFName)
If GTFResult = 0 Then
GTFErrorCode = Marshal.GetLastWin32Error
End If
GTFResult is 0 (failure) after the call to GetTempFileName, and
GTFErrorCode is 127. Note that I am forcing an error because "x:\temp"
does not exist (I have no X drive), but the error-code seems to be
wrong.
Looking at this and your last example, I realize what the problem is...
You aren't adding the SetLastError:=True to your DllImport attribute.
Without that, the api error code is not saved.

Now for a couple of api suggestions...

1) You don't need to null terminate your strings (the Chr(0)), the
marshaller will take care of that for you. That was true in VB6 as
well as .NET. It won't hurt anything really, but it is just extra
overhead that doesn't need to happen.

2) Don't hard code to the A/W versions of your calls. The runtime
marshaller can work that out for you as well. In other words, your
declare would look like:

<DllImport("kernel32", CharSet:=CharSet.Auto, SetLastError:=True)>
_
Private Function GetTempFileName( _
ByVal lpPathName As String, _
ByVal lpPrefixString As String, _
ByVal uUnique As Integer, _
ByVal lpTempFileName As StringBuilder) As Integer

End Function

The runtime will call the W function on systems were it is available,
avoiding the extra string conversions required for the A function on NT
boxes.

3) Why don't you just use the VB declare syntax?
Private Declare Auto Function GetTempFileName Lib "kernel" (.....) As
Integer
That will set all the necessary attribute fields (like SetLastError).

Don't take any of the above as critizism, just friendly advice. Anyway
here is my code for your example:

Option Explicit On
Option Strict On

Imports System
Imports System.Text
Imports System.ComponentModel
Imports System.Runtime.InteropServices

Module Module1

<DllImport("kernel32", CharSet:=CharSet.Auto, SetLastError:=True)>
_
Private Function GetTempFileName( _
ByVal lpPathName As String, _
ByVal lpPrefixString As String, _
ByVal uUnique As Integer, _
ByVal lpTempFileName As StringBuilder) As Integer
End Function

'Private Declare Auto Function GetTempFileName Lib "kernel32" ( _
' ByVal lpPathName As String, _
' ByVal lpPrefixString As String, _
' ByVal uUnique As Integer, _
' ByVal lpTempFileName As StringBuilder) As Integer

Sub Main()
Dim tempFile As New StringBuilder(260)

If GetTempFileName("x:\temp", "zzzz", 0, tempFile) = 0 Then

Dim exception As New
Win32Exception(Marshal.GetLastWin32Error())
Console.WriteLine( _
"The error code was {0} and the message was {1}", _
exception.ErrorCode, exception.Message)

End If
End Sub
End Module

--
Tom Shelton [MVP]

Jul 31 '06 #5
Lee
Tom:

Much much thanks for the help and advice.

1) The missing "SetLastError" was a brain fart on my part :) -- once I
added that, things worked as expected.

2) I wasn't sure about the Chr(0)'s -- but I figured better safe than
sorry. Glad they are not needed.

3) I did decide to change the declaration syntax to the shorter Declare
syntax -- I'm not sure why I was using the empty-function syntax -- but
the Declare syntax works just fine.

Thanks again for the help and advice.

--
// Lee Silver
// Information Concepts Inc.
//
// Converting Data into Information since 1981

Tom Shelton wrote:
Looking at this and your last example, I realize what the problem is...
You aren't adding the SetLastError:=True to your DllImport attribute.
Without that, the api error code is not saved.

Now for a couple of api suggestions...

1) You don't need to null terminate your strings (the Chr(0)), the
marshaller will take care of that for you. That was true in VB6 as
well as .NET. It won't hurt anything really, but it is just extra
overhead that doesn't need to happen.

2) Don't hard code to the A/W versions of your calls. The runtime
marshaller can work that out for you as well. In other words, your
declare would look like:

<DllImport("kernel32", CharSet:=CharSet.Auto, SetLastError:=True)>
_
Private Function GetTempFileName( _
ByVal lpPathName As String, _
ByVal lpPrefixString As String, _
ByVal uUnique As Integer, _
ByVal lpTempFileName As StringBuilder) As Integer

End Function

The runtime will call the W function on systems were it is available,
avoiding the extra string conversions required for the A function on NT
boxes.

3) Why don't you just use the VB declare syntax?
Private Declare Auto Function GetTempFileName Lib "kernel" (.....) As
Integer
That will set all the necessary attribute fields (like SetLastError).

Don't take any of the above as critizism, just friendly advice. Anyway
here is my code for your example:

Option Explicit On
Option Strict On

Imports System
Imports System.Text
Imports System.ComponentModel
Imports System.Runtime.InteropServices

Module Module1

<DllImport("kernel32", CharSet:=CharSet.Auto, SetLastError:=True)>
_
Private Function GetTempFileName( _
ByVal lpPathName As String, _
ByVal lpPrefixString As String, _
ByVal uUnique As Integer, _
ByVal lpTempFileName As StringBuilder) As Integer
End Function

'Private Declare Auto Function GetTempFileName Lib "kernel32" ( _
' ByVal lpPathName As String, _
' ByVal lpPrefixString As String, _
' ByVal uUnique As Integer, _
' ByVal lpTempFileName As StringBuilder) As Integer

Sub Main()
Dim tempFile As New StringBuilder(260)

If GetTempFileName("x:\temp", "zzzz", 0, tempFile) = 0 Then

Dim exception As New
Win32Exception(Marshal.GetLastWin32Error())
Console.WriteLine( _
"The error code was {0} and the message was {1}", _
exception.ErrorCode, exception.Message)

End If
End Sub
End Module

--
Tom Shelton [MVP]
Jul 31 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: build | last post by:
G'day All, I'm using code below to check a path selected by a user. Can anyone pick holes in it please? The more critical you are the better. tia build 'GET SOURCE PATH...
11
by: Wolfgang Kaml | last post by:
Hello All, I have been working on this for almost a week now and I haven't anything up my sleeves anymore that I could test in addition or change.... Since I am not sure, if this is a Windows...
2
by: Skybuck Flying | last post by:
Hi, This is a somewhat cleaned up version 0.02 of the nrand48() routine. There are still a few issues: This code needs brackets but where ? X = (uint64) xsubi << 32 | (uint32) xsubi << 16...
11
by: zhong | last post by:
Error Message: Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention...
3
by: Caspy | last post by:
I just get stuck on how to check if a user is a member of network (domain). I am building an internal tracking system with ASP.Net with Form authentication. When an user is added into the system,...
1
by: Dave Brown | last post by:
I am attempting to post to a url (https://FakeURL/logon.asp) using the HttpWebRequest class. The response for a succesful post will contain the html for the logon user's default page. We've...
2
by: Steve JORDI | last post by:
Hi, I'm having a little trouble trying to update a page content when the user clicks a check box. Basically, I need to reload a page to update its content depending on that checkbox status. I...
17
by: Klaas Vantournhout | last post by:
Hi all, I was wondering if it is possible if you can check in a function if one of the arguments is temporary. What I mean is the following. A is a class, foo is a function returning a class...
173
by: Marty James | last post by:
Howdy, I was reflecting recently on malloc. Obviously, for tiny allocations like 20 bytes to strcpy a filename or something, there's no point putting in a check on the return value of malloc....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.