<DllImport("user32.dll",SetLastError:=true)>_PrivateSharedFunctionGetKeyboardState(ByValkeyState() As Byte) As Boolean End Function'or...Private Declare Function GetKeyboardState Lib "user32" (ByValkeyState() As Byte) As Boolean
C#:
usingSystem;usingSystem.Runtime.InteropServices;usingSystem.ComponentModel;namespacePInvokeSample{publicstaticclassKeyboard{publicstaticintGetKeyState(){byte[]keys=newbyte[256]; //Get pressed keysif(!NativeMethods.GetKeyboardState(keys)){interr=Marshal.GetLastWin32Error();thrownewWin32Exception(err);}for(inti=0;i<256;i++){bytekey=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;}}}
using System;
using System.Runtime.InteropServices;
namespace PInvokeSample {
internal static class NativeMethods {
[DllImport("User32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetKeyboardState(byte[] lpKeyState);
}
}
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
Private Shared keyState() As Byte
<DllImport("user32.dll")> _
Private Shared Function GetKeyboardState(ByVal keyState() As Byte) As Boolean
End Function
Private Shared Sub Update()
keyState = New Byte(256) {}
Dim result As Boolean = GetKeyboardState(keyState)
' 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