Is it possible to send Alt+Space to command prompt by using WSH javascript sendKeys method?

1.4k Views Asked by At

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.

2

There are 2 best solutions below

1
On

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.

0
On

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?