取得按下按鍵

使用API

API名稱:GetCursorPos
動態連結程式庫: user32.dll


程式說明

偵測按下按鍵,並顯示在textbox中。
本範例可偵測Ctrl、ALT、Shift。
需要更多常數,VB6請使用API檢視員查詢,VB.NET可使用David Ross Goben製作的.NET API檢視員,本人翻譯了此作品,請按此了解


特殊類別

使用常數:

Const VK_LSHIFT = &HA0
Const VK_LCONTROL = &HA2
Const VK_LMENU = &HA4
Const VK_RSHIFT = &HA1
Const VK_RCONTROL = &HA3
Const VK_RMENU = &HA5

VB6程式碼

Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
    
Private Const VK_LSHIFT = &HA0
Private Const VK_LCONTROL = &HA2
Private Const VK_LMENU = &HA4
Private Const VK_RSHIFT = &HA1
Private Const VK_RCONTROL = &HA3
Private Const VK_RMENU = &HA5
'詳細用API檢視員查 關鍵字:VK_()常數

Private Sub Timer1_Timer()
    Dim msg As String
    If GetAsyncKeyState(VK_LSHIFT) And &H8000 Then msg = msg & "LSHIFT "
    If GetAsyncKeyState(VK_LCONTROL) And &H8000 Then msg = msg & "LCTRL "
    If GetAsyncKeyState(VK_LMENU) And &H8000 Then msg = msg & "LALT "
    
    If GetAsyncKeyState(VK_RSHIFT) And &H8000 Then msg = msg & "RSHIFT "
    If GetAsyncKeyState(VK_RCONTROL) And &H8000 Then msg = msg & "RCTRL "
    If GetAsyncKeyState(VK_RMENU) And &H8000 Then msg = msg & "RALT "
    Text1.Text = msg
End Sub

VB.NET程式碼

Imports System.Runtime.InteropServices

Public Class Form1
    Const VK_LSHIFT = &HA0
    Const VK_LCONTROL = &HA2
    Const VK_LMENU = &HA4
    Const VK_RSHIFT = &HA1
    Const VK_RCONTROL = &HA3
    Const VK_RMENU = &HA5

    Private Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As IntPtr) As Short

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Select Case True
            Case GetAsyncKeyState(Keys.LControlKey)
                TextBox1.Text = "Left Control"
            Case GetAsyncKeyState(Keys.RControlKey)
                TextBox1.Text = "Right Control"
            Case GetAsyncKeyState(Keys.LShiftKey)
                TextBox1.Text = "Left Shift"
            Case GetAsyncKeyState(Keys.RShiftKey)
                TextBox1.Text = "Right Shift"
            Case GetAsyncKeyState(Keys.LWin)
                TextBox1.Text = "Left Win"
            Case GetAsyncKeyState(Keys.RWin)
                TextBox1.Text = "Right Win"
            Case GetAsyncKeyState(Keys.LMenu)
                TextBox1.Text = "Left Menu"
            Case GetAsyncKeyState(Keys.RMenu)
                TextBox1.Text = "Right Menu"
        End Select
    End Sub
End Class

下載