Zyzyx
Zyzyx

Reputation: 534

cursor position using GetCursorPos gives PInvokeStackImbalance error

I'm trying to obtain my cursor position using GetCursorPos, but it gives me the error

Managed Debugging Assistant 'PInvokeStackImbalance' : 'A call to PInvoke function 'MoveClickApp!MoveClickApp.Module1::GetCursorPos' has unbalanced the stack. This is likely because the managed PInvoke signature does not match the unmanaged target signature. Check that the calling convention and parameters of the PInvoke signature match the target unmanaged signature.'

I'm unable to figure out what that means or how to proceed. Any ideas?

Public Declare Function GetCursorPos Lib "user32" (ByVal lpPoint As POINTAPI) As UInt32

Public Structure POINTAPI
    Dim x As UInt32
    Dim y As UInt32
End Structure

Public Function GetX() As UInt32
    Dim n As POINTAPI
    GetCursorPos(n)
    GetX = n.x
End Function

Public Function GetY() As UInt32
    Dim n As POINTAPI
    GetCursorPos(n)
    GetY = n.y
End Function

Alternatives to this method would also be appreciated

Upvotes: 0

Views: 1379

Answers (1)

John Koerner
John Koerner

Reputation: 38077

You need to include the LayoutKind on your structure, also you should be using the Integer type for x and y, not uint32. Finally, the return type of the method is a BOOL not a Uint32 and you should probably marshal the result:

<System.Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Sequential)>
Public Structure POINTAPI
    Dim x As Integer
    Dim y As Integer
End Structure

<DllImport("user32.dll", ExactSpelling := True, SetLastError := True)> _
Public Shared Function GetCursorPos(ByRef lpPoint As POINTAPI) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function

Pinvoke.net is a great resource to use when invoking to Win32 APIs. Their sample has this method here.

Upvotes: 2

Related Questions