"PInvokeStackImbalance occurred" and Windows API methods from .Net

Managed Debugging Assistant Exception (MDA):

PInvokeStackImbalance occurred

If you've found this entry, you're probably inside of Visual Studio using pInvokes to call some functionality in the Windows API. The above error is actually a Manage Debugging Assistant (MDA) error.

In some scenarios, you can turn the MDA off and your application may perform fine. In others, you probably need to fix the underlaying issue (and then in some cases certain MDA's can't be turned off at all as was the case with mine). If you do want to turn it off you can view all MDA's and turn them off in Visual Studio via "Debug->Exceptions->Managed Debugging Assistants".

In my case, I had misdefined the pInvoke call and was passing in an incorrect variable type to the API. I was calling SetWindowPos in user32 and had defined the parameters as Long's instead of Integers. Changing these to Integers fixed my problem. If I had to guess, most times the above MDA will be thrown because of an incorrect type.