The problem is with this line:

‘ retval is NULL if API failed to set focus on requested window

If retval.Equals(0) Then

Remember, the retval for this API is an IntPtr, not an integer. Even if the IntPtr is null, the exception will not get thrown.

You can do

You can do

If retval.ToInt32.Equals(0) Then

Or

If retval.ToInt32 = 0 Then

Or

If retval.Equals(IntPtr.Zero) Then

But not

If retval.Equals(0) Then

When you’re dealing with lots and lots of APIs in an automation framework, this sort of gotcha might not be as blatantly obvious as it was tonight.