What I’m trying to do is tracing Ctrl+Tab keypress on my main form using following code
<DllImport("user32.dll", PreserveSig:=False)>
Private Shared Function GetAsyncKeyState(ByVal vKey As System.Windows.Forms.Keys) As Short
End Function
Private ReadOnly Property CtrlPressed As Boolean
Get
Dim keyval As Integer
keyval = GetAsyncKeyState(Keys.ControlKey)
If keyval = 0 Then
CtrlPressed = False
Else
CtrlPressed = True
End If
End Get
End Property
But while calling the property CtrlPressed I’m getting PInvokeStackImbalance error. I’m sure with declaration of GetAsyncKeyState and also have imported InteropServices but the CtrlPressed property has something syntactically wrong. How can I solve this issue?
Thanks
A stack imbalance error almost always means that your P/Invoke definition signature is wrong. The first thing to do is check carefully all of your types and make sure that they match the documented signature for the native function. In this case, it looks good.
Except that you’ve set
PreserveSigtoFalse, and I’m not really sure why. As the documentation for that field indicates, it is designed for use with unmanaged methods that return an error code (for example, anHRESULTcode). It instructs the runtime to automatically convert those error codes into exceptions. But theGetAsyncKeyStatemethod doesn’t return an error code, so enabling this option doesn’t make a lot of sense.The following code works fine for me:
Make sure that you’ve paid close attention to the documentation for the
GetAsyncKeyStatefunction. Specifically, the section on return values: