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
If retval.ToInt32.Equals(0) Then
If retval.ToInt32 = 0 Then
If retval.Equals(IntPtr.Zero) 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.