Reputation: 21
the GetKeyState() in my code is not evaluating correctly .. when i use this :
bool ctrlDown = GetKeyState(VK_LCONTROL) != 0 || GetKeyState(VK_RCONTROL) != 0;
in my code its not coming back with the correct info.. its fired on all key events and its being evaluated as true even when other keys are pressed.. can anyone see anything im doing wrong in this code ?
i load it up here :
[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
public static extern short GetKeyState(int nVirtKey);
Then i call the "VK_LCONTROL & VK_RCONTROL" var's and fill them :
public const int VK_LCONTROL = 0xA2;
public const int VK_RCONTROL = 0xA3;
and then i call it in this function:
private int KbHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
var hookStruct = (KbLLHookStruct)Marshal.PtrToStructure(lParam, typeof(KbLLHookStruct));
bool ctrlDown = GetKeyState(VK_LCONTROL) != 0 || GetKeyState(VK_RCONTROL) != 0;
if (nCode >= 0 && wParam == (IntPtr)WM_KEYUP && hookStruct.vkCode == 0x56 && ctrlDown == true)
{
MessageBox.Show("Message : KEY UP");
ComboHit = false;
}
// Pass to other keyboard handlers. Makes the Ctrl+V pass through.
return CallNextHookEx(_hookHandle, nCode, wParam, lParam);
}
when i check so see what the " GetKeyState(VK_LCONTROL) " is returning .. its alternates back and forth between 0 & 1, i knwo that MS says it should do this : "Retrieves the status of the specified virtual key. The status specifies whether the key is up, down, or toggled (on, off—alternating each time the key is pressed). "
why would i want this ?.. and can i make it evaluate the keys up or down position accurately ?
Upvotes: 0
Views: 9077
Reputation: 51349
Why not just use Control.ModifierKeys?
Something like this?
public partial class myForm : Form
{
public myForm()
{
InitializeComponent();
}
private void myForm_Load(object sender, EventArgs e)
{
KeyPreview = true;
KeyUp += (s, ek) =>
{
if (ek.KeyCode == Keys.V && ModifierKeys.HasFlag(Keys.Control))
MessageBox.Show("Yerp, it done happened");
};
}
}
Upvotes: 1
Reputation: 56934
What exactly are you trying to do ? I think perhaps you could take a look at the GetKeyboardState method
https://stackoverflow.com/a/709641/55774
Upvotes: 0
Reputation: 12276
To test if a key is down, you need to check the high order bit:
(GetKeyState(vk) & 0x8000)
Upvotes: 9