1

Following code doesn't work on Command Prompt. It sends only " ". Why? I'm using windows7.

[js]
var shellApp = new ActiveXObject("Wscript.Shell");
shellApp.appActivate("C:\\Windows\\system32\\cmd.exe"); //Other apps seem to work.
WScript.Sleep(1000);
shellApp.sendKeys("%( )");

I want to paste a string. To do that I need to press Alt+Space in command prompt. WSH solution is the best. I can't install and use third party thing because it's not allowed in my enviroment.

Thanks.

chiwangc
  • 3,566
  • 16
  • 26
  • 32
Kei Minagawa
  • 4,395
  • 3
  • 25
  • 43
  • 1
    Enable "Quick Edit Mode" for `CMD` and you'll be able to paste text with a single right click (see [here](http://stackoverflow.com/a/17352658/1630171)). Don't fiddle around with `SendKeys`. – Ansgar Wiechers Dec 03 '13 at 18:04
  • I had the same problem, but found a workaround by invoking powershell. See [this answer](http://stackoverflow.com/a/27134310/1683264) for details. – rojo Nov 25 '14 at 19:25

2 Answers2

1

I finally solved it myself. Here is my answer. To run this code you needs Excel app. Thanks all.

[js]
//Be careful. It seems completely emulate key press.
//You need Execel app to run this code.
var shellApp = new ActiveXObject("Wscript.Shell");
var ex = WScript.CreateObject("Excel.Application");
shellApp.appActivate("C:\\Windows\\system32\\cmd.exe")
ex.ExecuteExcel4Macro("CALL(\"user32\",\"keybd_event\",\"JJJJJ\",164,56,1,0)");
ex.ExecuteExcel4Macro("CALL(\"user32\",\"keybd_event\",\"JJJJJ\",32,57,1,0)");
ex.ExecuteExcel4Macro("CALL(\"user32\",\"keybd_event\",\"JJJJJ\",32,57,3,0)");
ex.ExecuteExcel4Macro("CALL(\"user32\",\"keybd_event\",\"JJJJJ\",164,56,3,0)");
shellApp.sendKeys("ep");//Pasting clipboard text

Refference: How to send Alt+space to console window?

Community
  • 1
  • 1
Kei Minagawa
  • 4,395
  • 3
  • 25
  • 43
0

Do you want to paste a string or do you want to past the Clipboard contents? To paste the clipboard, you can use this (it is written in VBScript, but you can rebuild it in JavaScript):

dim shellApp
Set shellApp = Wscript.CreateObject("Wscript.Shell")
shellApp.appActivate "C:\Windows\system32\cmd.exe"
WScript.Sleep 1000

Dim objHTML
Set objHTML = CreateObject("htmlfile")
shellApp.sendKeys objHTML.ParentWindow.ClipboardData.GetData("Text")

Drawback: you need to escape any special character.

AutomatedChaos
  • 7,267
  • 2
  • 27
  • 47
  • I know what you mean. If all char of string is consist of ascii char, it works well. But what if string contains multi-byte char. Actually I want to send multi-byte char to command-prompt. That's why I need to emulate "Alt+Space". I can paste multi-byte string by "Alt + Space" and press "e" and "p". I just want to emulate it. – Kei Minagawa Dec 03 '13 at 15:37