GetKeyState function in C#
Dear Code Gurus,
I have been just recently converted to C# from C++ and I am still trying to learn new concepts. In C++ there was a function that provided me with an answer about the state of a certain keyboard keys instantly - I only used this function to decide if a certain key is pressed or not. For example, to see if a SHIFT key down I used the following code in C++:
Code:
BOOL ShiftKeyDown = (::GetKeyState(VK_LSHIFT)<0 || ::GetKeyState(VK_RSHIFT)<0);
Is there something like that available in C#? If not, what is the best way to find out if a particular key is down or not?
So far, I only found one solution to that using KeyDown and KeyUp events but it sort of seems to complicated for me.
Thank you for your help!
Re: GetKeyState function in C#
The solution is to... use the KeyPress, KeyDown, and KeyUp events :). You don't need to poll because you have these events. How about telling us where you got hung up using them and we can then help you out.
Re: GetKeyState function in C#
BigEd781,
I was using the functions that you mention adding them as "KeyEventHandler" to my form and correspondingly setting some bool variables depending on what the user pressed, however the tracking of those events is kind of difficult, when the form itself is not in focus and when those events itself are used as variables to some other functions that do not immediately follow the "KeyDown" or "KeyUp" events. I have found the following solution on the internet and it seems to work fine for me now - I can just call a function IsKeyDown from the code below directly in the function where the key state is needed. Can you provide any comments? Thanks for your help.
Code:
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace MouseKeyboardStateTest
{
public abstract class Keyboard
{
[Flags]
private enum KeyStates
{
None = 0,
Down = 1,
Toggled = 2
}
[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
private static extern short GetKeyState(int keyCode);
private static KeyStates GetKeyState(Keys key)
{
KeyStates state = KeyStates.None;
short retVal = GetKeyState((int)key);
//If the high-order bit is 1, the key is down
//otherwise, it is up.
if ((retVal & 0x8000) == 0x8000)
state |= KeyStates.Down;
//If the low-order bit is 1, the key is toggled.
if ((retVal & 1) == 1)
state |= KeyStates.Toggled;
return state;
}
public static bool IsKeyDown(Keys key)
{
return KeyStates.Down == (GetKeyState(key) & KeyStates.Down);
}
public static bool IsKeyToggled(Keys key)
{
return KeyStates.Toggled == (GetKeyState(key) & KeyStates.Toggled);
}
}
}
Re: GetKeyState function in C#
I don't know that I really follow what you are trying to accomplish. If you want to set global keyboard hooks than yes, you will need to use the Windows API. However, if that is not the case than the KeyX events should be fine. If I knew the problem that you were trying to solve than I could provide an example.