SAPIEN Solutions

SAPIEN homepage
PrimalScript script editor+ide
PrimalScope script debugger
Free Tools script utilities
SAPIEN Press tech books
ScriptingAnswers.com learn+share
ScriptingOutpost.com online store
Blog.Sapien.com official blog
Contact Us

 

Sending keystrokes to applications

 The last-resort way of automating anything using VBScript is to launch a GUI application and just send keystrokes (but not mouse movement or clicks - try AutoIt if you need mouse control, too). Here’s an example, using Notepad, of how sending keystrokes works. Note that this takes a lot of trial, error, and careful documentation of the necessary keystrokes in order to get it working.

  1. '
  2. ' ScriptingAnswers.com Essentials - by Don Jones
  3. '
  4. ' SendKeys example
  5. ' This shows how to automate the Windows GUI (or any GUI app)
  6. ' by sending keystrokes to it from a VBScript


  7. 'first we'll launch Notepad - this could be ANY app
  8. 'we'll specify that the script NOT wait for it
  9. 'to finish running
  10. Dim objShell
  11. Set objShell = CreateObject("WScript.Shell")
  12. objShell.Run "C:\Windows\System32\Notepad.exe",,False

  13. 'we will wait a second for the app to start
  14. WScript.Sleep 1000

  15. 'now we need to activate the windows. we need it's window
  16. 'title, which by experimentation we've determined Is
  17. '"Untitled - Notepad." You don't need the EXACT title;
  18. 'Windows will try to activate the first matching window
  19. 'it finds
  20. objShell.AppActivate "Untitled - Notepad"

  21. 'now we can send keystroked - see the WshShell docs
  22. 'for details on what this can Do

  23. 'we'll start with simple text
  24. objShell.SendKeys "Hello, scripter "

  25. 'to send a square bracket you have to enclose it in curly braces
  26. objShell.SendKeys "{[}If indeed you are a scripter{]}"

  27. 'special keys have a name you can send
  28. objShell.SendKeys "{HOME}To whom it may concern:{ENTER}{ENTER}"

  29. 'if you're controlling a GUI, these might be useful:
  30. ' function keys are {F1}, {F2} and so forth
  31. ' Use +{F3} for Shift+F3, ^{F4} for Ctrl+F4, and %{F5} for Alt+F5
  32. ' Tab is {TAB}, backspace is {BACKSPACE}, Enter is {ENTER} pr ~
  33. ' Escape is {ESC}. The arrows are {LEFT} {RIGHT} {UP} and {DOWN}
  34. ' You can add + for Shift, ^ for Ctrl, and % for Alt to any of these
  35. ' Usually, just type the key's face name in {} and you've got it
  36. ' About the only thing you can't send is PrintScreen
[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags: , , ,

Leave a Reply


Entries (RSS) and Comments (RSS).