GetKeyboardState (user32)
Last changed: -174.107.131.200

.
Summary

C# Signature:

[DllImport("user32.dll")]
static extern bool GetKeyboardState(byte [] lpKeyState);

VB Signature:

    <DllImport("user32.dll")> _
    Private Shared Function GetKeyboardState(ByVal keyState As IntPtr) As Boolean
    End Function

Notes:

None.

Tips & Tricks:

Please add some!

Sample Code:

Imports System.Runtime.InteropServices

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Me.Text = "Caps:" & NativeMethods.CapsLockState.ToString
    Me.Text &= ", Num: " & NativeMethods.NumLockState.ToString
    Me.Text &= ", Scroll: " & NativeMethods.ScrollLockState.ToString
    End Sub

End Class

Public Class NativeMethods

    Private Shared keyState() As Byte

    ' If there is a BETTER WAY to marshal this. Please enlighten...
    <DllImport("user32.dll")> _
    Private Shared Function GetKeyboardState(ByVal keyState As IntPtr) As Boolean
    End Function

    Private Shared Sub Update()
    ' Newerize the array...
    keyState = New Byte(255) {}
    ' Allocate a blob of memory to hold the bytes
    Dim ptr As IntPtr = Marshal.AllocHGlobal(256)
    ' Send the pointer to the memory to the function
    Dim result As Boolean = GetKeyboardState(ptr)
    ' If we got a favourable result then copy the bytes to the array
    If result = True Then
        Marshal.Copy(ptr, keyState, 0, keyState.Length)
    End If
    ' Always free your memory, or else there will be trouble
    Marshal.FreeHGlobal(ptr)
    ' Check for error:
    If result = False Then
        Debug.WriteLine("GetKeyBoardState error: " & Marshal.GetLastWin32Error)
        Throw New Exception("GetKeyBoardState error: " & Marshal.GetLastWin32Error)
    End If
    End Sub

    Public Enum LightState
    Off
    [On]
    End Enum

    ' Example - the keyboard lights...

    Public Shared ReadOnly Property CapsLockState() As LightState
    Get
        Update()
        Dim isOn As Boolean = (keyState(Keys.CapsLock) = 1)
        Return IIf(isOn, LightState.On, LightState.Off)
    End Get
    End Property

    Public Shared ReadOnly Property NumLockState() As LightState
    Get
        Update()
        Dim isOn As Boolean = (keyState(Keys.NumLock) = 1)
        Return IIf(isOn, LightState.On, LightState.Off)
    End Get
    End Property

    Public Shared ReadOnly Property ScrollLockState() As LightState
    Get
        Update()
        Dim isOn As Boolean = (keyState(Keys.Scroll) = 1)
        Return IIf(isOn, LightState.On, LightState.Off)
    End Get
    End Property

End Class

Alternative Managed API:

Do you know one? Please contribute it!

Documentation