为什么GetAsyncKeyState在MS Excel上不起作用

时间:2014-04-17 15:28:56

标签: vb.net

我编写了简单的程序捕获,以便在运行程序时按下女巫键。它工作正常,但它不适用于ms excel。我无法弄清问题在哪里。谁有人可以帮忙?我是编程新手。

Private Declare Function GetAsyncKeyState Lib "user32.dll" (ByVal vkey As Integer) As Integer

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

Dim Result as integer
For i = 1 to 255
       Result = GetAsyncKeyState(i)
       If Result = -32767 then
             textbox1.text = Cstr(chr(i))
       End If
Next

End Sub

1 个答案:

答案 0 :(得分:1)

GetAsyncKeyState的正确声明是:

<DllImport("user32.dll")> _
Public Shared Function GetAsyncKeyState(ByVal vKey As System.Windows.Forms.Keys) _  
                                        As Short
End Function

GetAsyncKeyState不能那样工作。你应该检查返回值的最高位(这是短的):

If (Result And &H8000) <> 0 then 'the key is pressed
    textbox1.text = Cstr(chr(i))
End If

您还应该检查Result是否为zero

编辑,循环必须来自1 to 254而不是255!在计时器滴答:

Timer1.Enabled = False

Dim Result As Short
Dim i As Integer

For i = 1 To 254
    Result = GetAsyncKeyState(CType(i, Keys))
    If (Result And &H8000) <> 0 Then
        TextBox1.Text = CStr(Chr(i))
    End If
Next

Timer1.Enabled = True

瓦尔特