Evren Ozturk
Evren Ozturk

Reputation: 928

GetAsyncKeyState on windows 7 x64

I'm trying to use GetAsyncKeyState(i) on windows7 x64 with C# to get pressed keys. It works perfect on x86. Here are my codes:

[DllImport("user32.dll")]
public static extern int GetAsyncKeyState(long vKey);
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true, CallingConvention = CallingConvention.Winapi)]
public static extern short GetKeyState(int keyCode); 

        search = false;
        int key_my;
        for (i = 0; i < 255; i++)
        {
            key_my = GetAsyncKeyState(i); // this should return -3.... but it does 46...........
            if ( key_my == (System.Int16.MinValue + 1))
            { search = true; break; }
        }
        if ( search == true)
        {
           ...//using if to keys here.
        }

any IDEA?

Upvotes: 0

Views: 5022

Answers (2)

john k
john k

Reputation: 6611

Though this question has already been answered correctly, I'd like to point out my experience using this answer and that putting it in one line does not work.

        if (GetAsyncKeyState(27) == (System.Int16.MinValue + 1)) 

does NOT work.

                int key_my = GetAsyncKeyState(27); 
                if (key_my == (System.Int16.MinValue + 1))

does work.

(I don't know why.)

Upvotes: 0

JaredPar
JaredPar

Reputation: 755557

The GetAsyncKeyState function should have a return type of short not int and it's parameter should be typed to int not long

[DllImport("user32.dll")]
public static extern short GetAsyncKeyState(int vKey);

Upvotes: 5

Related Questions