getkeyboardstate

C# Signature:

[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetKeyboardState(byte [] lpKeyState);

VB Signature:

<DllImport("user32.dll", SetLastError := true)> _
    Private Shared Function GetKeyboardState(ByVal keyState() As Byte) As Boolean
    End Function

'or...
Private Declare Function GetKeyboardState Lib "user32" (ByVal keyState() As Byte) As Boolean

C#:

using System;
    using System.Runtime.InteropServices;
    using System.ComponentModel;

    namespace PInvokeSample {
        public static class Keyboard {

         public static int GetKeyState(){
            byte[] keys = new byte[256];

            //Get pressed keys
            if(!NativeMethods.GetKeyboardState(keys)){
                int err = Marshal.GetLastWin32Error();
                throw new Win32Exception(err);
            }

            for(int i = 0; i < 256; i++){

             byte key = keys[i];

             //Logical 'and' so we can drop the low-order bit for toggled keys, else that key will appear with the value 1!
             if((key & 0x80) != 0){

            //This is just for a short demo, you may want this to return
            //multiple keys!
                return (int)key;
             }
            }
            return -1;
          }
          }
    }

C#:

VB:

VB:

Alternative Managed API:

Última actualización