sending ctrl+c using sendkeys in ruby

wani picture wani · Aug 2, 2011 · Viewed 6.9k times · Source

I need to close the command prompt window using sendkeys function, but when I used the below code it did not work as running of some betch file is in progress so its not taking these below options.

require 'win32ole'
system("start cmd.exe")
sleep(5)
# Create an instance of the Wscript Shell:
wsh = WIN32OLE.new('Wscript.Shell')

# Try to activate the command window:
if wsh.AppActivate('cmd.exe')    
  sleep(1)    
  wsh.SendKeys('cd \\')
  wsh.SendKeys('{ENTER}')
  # change the directory path where mtn folder is residing   
  wsh.SendKeys('cd ')  
  wsh.SendKeys "C://mtn-3//mtn-2.2//" 
  wsh.SendKeys('{ENTER}')  
  wsh.SendKeys('cd bin')  
  wsh.SendKeys('{ENTER}')  
  #run the cad test node file  
  wsh.SendKeys('CadTestNode.bat')  
  wsh.SendKeys('{ENTER}')
  wsh1.SendKeys('Exit') 
  wsh1.SendKeys('{ENTER}') 

I also tried replacing last two lines with the below to terminate the process.

  wsh.SendKeys "^(c)"                 
  wsh.SendKeys('{ENTER}')

but still it's not able to terminate the process running in command prompt.

Is there any other way to terminate the batch process running in command prompt window?

Answer

Douglas picture Douglas · Dec 7, 2016

Try this:

wsh.SendKeys("^C")

In the MSDN SendKeys Method specifies the following characters for this keys:

SHIFT: +

CTRL: ^

ALT: %

Examples:

wsh.SendKeys("+{TAB}") # SHIFT+TAB

wsh.SendKeys("^V")     # CTRL+V

wsh.SendKeys("%{F4}")  # ALT+F4