VB.Net 關於鍵盤 Num Lock 狀態 取得 / 改變

VB.Net 關於鍵盤 Num Lock 狀態 取得 / 改變

關於鍵盤 Num Lock 狀態 取得 / 改變

Public Class Form1

' API 宣告

' 模擬鍵盤動作

Private Declare Sub keybd_event Lib "user32" _

(ByVal bVk As Byte, ByVal bScan As Byte, _

ByVal dwFlags As Integer, ByVal dwExtraInfo As Integer)

' 轉換對應 虛擬鍵碼 (掃瞄碼)

Private Declare Function MapVirtualKey Lib "user32" Alias "MapVirtualKeyA" _

(ByVal wCode As Integer, ByVal wMapType As Integer) As Integer

' 顯示鍵盤 Num Lock 狀態

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click

' 取得 Num Lock 狀態顯示於 Label 上

If My.Computer.Keyboard.NumLock Then

Label1.Text = "[Num Lock] ON"

Else

Label1.Text = "[Num Lock] OFF"

End If

End Sub

' 切換鍵盤 Num Lock 狀態

Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click

' 宣告常式

Const VK_NUMLOCK = &H90 ' Num Lock

Const KEYEVENTF_KEYDOWN = &H0 ' KeyDown

Const KEYEVENTF_KEYUP = &H2 ' KeyUp

' 取得轉換後的 虛擬鍵碼

Dim intScanCode As Integer = MapVirtualKey(VK_NUMLOCK, 0)

' 模擬按下 Num Lock 鍵

keybd_event(VK_NUMLOCK, intScanCode, KEYEVENTF_KEYDOWN, 0) ' 按下

keybd_event(VK_NUMLOCK, intScanCode, KEYEVENTF_KEYUP, 0) ' 放開

End Sub

End Class