vb 自动按键 会卡的问题

来源:百度知道 编辑:UC知道 时间:2024/05/09 12:36:56
代码如下
Public StartTime As Long
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Private Sub Command1_Click()
Dim ReturnValue, I
ReturnValue = Shell("c:\windows\system32\notepad.exe", 1)
AppActivate ReturnValue
StartTime = 1
End Sub

Private Sub Command2_Click()
End
End Sub

Private Sub Form_Load()
Command1.Caption = "start"
Command2.Caption = "end"
Timer1.Interval = 1000
End Sub

Private Sub Timer1_Timer()
If StartTime = 1 Then
SendKeys "{TAB}"
Call Sleep(1000)
SendKeys "1"
Call Sleep(1000)
End If
End Sub

问题:运行后 在按键的时候 电脑会卡住2秒左右 大家帮我看看 谢谢了

运用sleep时,会让系统停止响应一下,不仅仅是你的应用程序..
所以,在需要延时的时候,可以使用变通的方法:

先添加下面这个过程:
Public Sub Delay(mSec As Long)
On Error GoTo ShowErr
Dim TStart As Single
TStart = Timer
While (Timer - TStart) < (mSec / 1000)
DoEvents
Wend
Exit Sub

然后你代码中的sleep换成: Delay (1000)

Private Sub Timer1_Timer()
If StartTime = 1 Then
SendKeys "{TAB}"
Call Sleep(1000)'这句话卡了一秒
SendKeys "1"
Call Sleep(1000)'这句话又卡了一秒
End If

解决办法:把这两句话去掉