Search code examples
.netpinvokecode-analysisportable-applications

.NET Portability Warning: CA1901 PInvoke Declarations Should Be Portable


When I add the following lines into my code

[DllImport("user32.dll")]
static extern void keybd_event(byte key, byte scan, int flags, int extraInfo);

and run a code analysis against Microsoft Basic Correctness Rules, I get a CA1901 warning. Basically, it complains the 4th parameter int extraInfo works fine on a 32-bit platform but a 64-bit integer type is expected on 64-bit platform.

When I modified the code into long extraInfo, the 64-bit platform requirement is met but the 32-bit platform is expecting a 32-bit integer.

How to solve this dilemma without suppressing the warning?


Solution

  • By using an IntPtr which is a platform-specific type that is used to represent a pointer or a handle:

    [DllImport("user32.dll")]
    static extern void keybd_event(byte key, byte scan, int flags, IntPtr extraInfo);