Question

I need to check if caps lock is pressed, and found a function that requires an int online.

[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern short GetKeyState(int keyCode);
Was it helpful?

Solution

From googling, I found this one:

void CheckKeyState()
{
   if ((GetKeyState(VK_CAPITAL) & 0x0001)!=0)
      AfxMessageBox("Caps Lock ON!");
   else
      AfxMessageBox("Caps Lock OFF!");
}

With VK_CAPITAL being 0x14.

So you could write in C#:

public void CheckKeyState()
{
   if ((GetKeyState(0x14) & 0x0001)!=0)
      System.Windows.Forms.MessageBox.Show("Caps Lock ON!");
   else
      System.Windows.Forms.MessageBox.Show("Caps Lock OFF!");
}

Of course, what Holger says makes a lot more sense than using the P/Invoke stuff.

OTHER TIPS

C# also has:

if (Control.IsKeyLocked(Keys.CapsLock))

Keys.CapsLock = 20 (0x14 in hex)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top