Make sendKeys faster

China☆狼群 提交于 2019-12-02 09:04:44

问题


I'm trying to create a program that will open "command prompt" and open a specific port using "sendKeys". Here is my code:

Set Keys = CreateObject("WScript.Shell")
oShell.ShellExecute "cmd.exe","runas", 1
Sleep(0.01)
Keys.sendKeys "{ENTER}"
Sleep(0.01)
Keys.sendKeys "rem Open TCP Port 407 inbound and outbound"
Keys.sendKeys "{ENTER}"
Keys.sendKeys "netsh advfirewall firewall add rule name=""EXAMPLE"" dir=out action=allow protocol=TCP localport=407"
Keys.sendKeys "{ENTER}"
Keys.sendKeys "netsh advfirewall firewall add rule name=""EXAMPLE""  protocol=TCP dir=out localport=407 action=""allow"""
Keys.sendKeys "{ENTER}"

I think that the keys are not fast enough.

I don't want to use Keys.run "cmd [code]" because then an Antivirus might think that the program is a virus.


回答1:


Instead of using SendKeys (which you would usually use a last resort for programs that don't have command-line support), you can use WShell to execute commands directly and get the output from StdOut or StdErr. The added advantage is you can check the return status and the output to see whether your commands succeeded or failed.

See my answer here as an example, but I'll include it here for your convenience:

Option Explicit

Const WshRunning = 0
Const WshFinished = 1
Const WshFailed = 2

Dim shell : Set shell = CreateObject("WScript.Shell")
Dim exec : Set exec = shell.Exec("ping.exe 127.0.0.1 -n 1 -w 500")

While exec.Status = WshRunning
    WScript.Sleep 50
Wend

Dim output

If exec.Status = WshFailed Then
    output = exec.StdErr.ReadAll
Else
    output = exec.StdOut.ReadAll
End If

WScript.Echo output

Alternatively, instead of executing multiple WScript shells in succession, you can write your commands into a pre-made batch file and execute that.




回答2:


There is another method to do this. Not expert with the antivirus software... You may check if this suites you.

Set oShell = CreateObject("WScript.Shell")

Set oExec = oShell.exec("%comspec%")

oExec.StdIn.Write "dir" & vbCrLf



回答3:


For anyone who wants to remove the delay: Instead of doing

Set Keys = CreateObject("WScript.Shell")
    Keys.sendKeys "a"
    Keys.sendKeys "{ENTER}"
    Keys.sendKeys "b"
    Keys.sendKeys "{ENTER}"
    Keys.sendKeys "c"
    Keys.sendKeys "{ENTER}

do

Set Keys = CreateObject("WScript.Shell")
Keys.sendKey "a{ENTER}b{ENTER}c{ENTER}"

It's messy, but it's WAY faster.



来源:https://stackoverflow.com/questions/45261870/make-sendkeys-faster

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!