Reputation: 3135
I ran into a situation where I needed to change the DLL Import statement I was using depending on the OS. I'm wondering if anyone else has observed this, knows why, or if there is a better way to handle this.
Here is a minimal code snippet showing the problem. It is a simple command line app that just outputs the status of the shift key.
using System;
using System.Runtime.InteropServices;
namespace Shift
{
class Program
{
[DllImport("user32.dll", SetLastError = true)]
public static extern short GetAsyncKeyState(ushort virtualKeyCode);
static void Main(string[] args)
{
Console.WriteLine("Shift is: " + GetAsyncKeyState(0x10));
}
}
}
The above works fine for me when ran on Windows 8.1 x64 or when built as 32-bits and run on Windows 7 x64. It does not however work on a Windows 7 system when compiled for x64. In that case GetAsyncKeyState always returns 0.
If I change the DLLImport to the following it then works on Windows 7 system when compiled for x64.
[DllImport("user32.dll", SetLastError = true)]
public static extern short GetAsyncKeyState(int virtualKeyCode);
Upvotes: 2
Views: 2209
Reputation: 612963
The original declaration is wrong. The documentation is here: https://msdn.microsoft.com/en-us/library/windows/desktop/ms646293.aspx
This gives the declaration as:
SHORT WINAPI GetAsyncKeyState(
_In_ int vKey
);
The correct p/invoke is:
[DllImport("user32.dll")]
public static extern short GetAsyncKeyState(int vKey);
Note that I have removed the setting of SetLastError
. The documentation makes no mention of SetLastError
being called.
Upvotes: 3