4

I'm am trying to send some keystrokes to a program. I have some example code below which works fine up until the final {Alt} command. I believe this is due to the window name changing from "Notepad1" to "NotePad2". Could anyone help me change the AppActivate path to "Notepad2" after the objShell.SendKeys "{Enter}" command?

Example:

Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "Notepad.exe"
Do Until Success = True
Success = objShell.AppActivate("NotepadPathA")
Loop
objShell.SendKeys "{F1}"
objShell.SendKeys "Secure06**"
objShell.SendKeys "{Enter}"
Shell.SendKeys "{Alt}"
Bond
  • 16,071
  • 6
  • 30
  • 53
David James
  • 51
  • 1
  • 1
  • 2

2 Answers2

4
  1. You're using Shell on your last line but you haven't defined it. Change it to objShell instead.
  2. To send the Alt key, use "%". For example:

    objShell.SendKeys "%"
    

    You would typically use this in a key combination. For example, to open the File menu in most programs, you would use Alt+F, or:

    objShell.SendKeys "%f"
    
  3. If your window title changes, or you need to activate a new window for whatever reason, just call AppActivate again:

    objShell.AppActivate "My new window title"
    
Bond
  • 16,071
  • 6
  • 30
  • 53
  • 2
    If this solved your issue, consider [accepting it as answer](http://stackoverflow.com/help/accepted-answer). – Bond Jul 31 '15 at 22:37
3

Each windows process has an identifier. If you store the process id for each notepad window, you can avoid worrying about finding the right window after its title changes.

Here is an example of opening two notepad files, activating by process id and sending keys.

Set objShell = WScript.CreateObject("WScript.Shell")

Function SendKeysTo (process, keys, wait)
    objShell.AppActivate(process.ProcessID)
    objShell.SendKeys keys
    WScript.Sleep wait
End Function

Set notepadA= objShell.Exec("notepad")
Set notepadB= objShell.Exec("notepad")
WScript.Sleep 500


SendKeysTo notepadA, "Hello I am Notepad A", 1000
SendKeysTo notepadB, "Hello I am Notepad B", 1000

Hopefully you can take a similar approach to solve your problem.

James Forbes
  • 1,487
  • 12
  • 15
  • No I dont think so, ive just changed that objShell.SendKeys "{Alt}" but i get the same error Line 9 , Char 1, Error "Invalid Procedure call or argument" Code: 800A005, Source MS VBScript runtime error. I believe the error is because after the {Enter} command the window changes name so i need to somehow reference that window instead. – David James Jul 30 '15 at 13:20
  • I've edited the answer to accommodate changing window titles. – James Forbes Jul 30 '15 at 22:36