Search code examples
rwindowsautomation

How can my R script check which window is active under windows?


I am trying to use the KeyboardSimulator package to automate something.

I would like to use the keyboard simulator package in R to hit "alt+tab" and then check if a window is open before continuing. Then it is safe for the script to hit "tab" until it hits the right text input box.

I know I can use

getWindowsHandles(which = "all")

to check the name of all open windows, but is there a way to check which window is active?

Furtheremore, is there a way to check the name of the text box?


Solution

  • Assuming you do know the handle name of the window you are planning to manipulate via library(KeyboardSimulator) here is a workaround:

    The following minimizes all opened windows and after that only restores the window of interest (here notepad++) so it is the active one:

    library(KeyboardSimulator)
    
    system2("C:\\Program Files (x86)\\Notepad++\\notepad++.exe", wait = FALSE) # run notepad++ asynchronously
    Sys.sleep(2) # wait for notepad++ window to be opened (for demo only - can be opened manually)
    all_handles <- getWindowsHandles(which = "all", minimized = TRUE)
    notepad_handle <- all_handles[grep("notepad", names(all_handles), ignore.case = TRUE)[1]] # search notepad++ handle and use the first match
    
    if(is.null(notepad_handle[[1]])){
      message("No 'notepad' handle available")
    } else {
      arrangeWindows(action = "minimize", windows = all_handles) # minimize all windows
      arrangeWindows(action = "restore", windows = notepad_handle) # restore notepad++ handle
      
      # use library(KeyboardSimulator) on the active window
      keybd.type_string("test")
      keybd.press('Tab')
      keybd.type_string("test")
    }