MsgBox and InputBox. The following code makes them available in JScript too.
To be the more compatible with VBScript it adds so-called "syntax sugar" -- several
vb.XXX constants corresponding to vbXXX constants in VBScript. The full original code is available by the following link js::win32::VBScript.js at jsxt.
Source
var vb = {};
vb.Function = function(func)
{
return function()
{
return vb.Function.eval.call(this, func, arguments);
};
};
vb.Function.eval = function(func)
{
var args = Array.prototype.slice.call(arguments[1]);
for (var i = 0; i < args.length; i++) {
if ( typeof args[i] != 'string' ) {
continue;
}
args[i] = '"' + args[i].replace(/"/g, '" + Chr(34) + "') + '"';
}
var vbe;
vbe = new ActiveXObject('ScriptControl');
vbe.Language = 'VBScript';
return vbe.eval(func + '(' + args.join(', ') + ')');
};
/**
*
* InputBox(prompt[, title][, default][, xpos][, ypos][, helpfile, context])
*
*/
var InputBox = vb.Function('InputBox');
/**
*
* MsgBox(prompt[, buttons][, title][, helpfile, context])
*
*/
var MsgBox = vb.Function('MsgBox');
Examples
Compare two codes below -- the first one is JScript and the second one is VBScript.JScript
var title, res, msg;
title = 'VBScript Emulating';
// The resulting string
res = InputBox('Enter a string', title);
// The message to be displayed
if ( res ) {
msg = 'You have entered: "' + res + '".';
} else {
msg = 'Nothing has been entered.';
}
// Displaying of the message
MsgBox(msg, 0, title);
VBScript
Dim title, res, msg
title = "VBScript Emulating"
' The resulting string
res = InputBox("Enter a string", title)
' The message to be displayed
If res <> "" Then
msg = "You have entered: " & Chr(34) & res & Chr(34) & "."
Else
msg = "Nothing has been entered."
End If
' Displaying of the message
MsgBox msg, 0, title
Thank you for posting this! This is excellent!
ReplyDeleteThis is a great post and it works on my Windows Seven PC at work, but my Windows Seven PC at home (64-bit) gives me the error that the automation server couldn't be created.
ReplyDeleteNice find! One thing that may be important to realize is that this code will only work on the 32-bit version of cscript/wscript.
ReplyDeleteAnother thing to realize is that this solution will not work for strings that have the linefeed character or the carriage return in them. Also, it would be nice if the constants that are available for the MsgBox function VBScript were automatically defined for JScript. I actually used your awesome find, modified it, and posted a more in-depth solution on my site (of course with a link back to here).
DeleteHi Chris,
DeleteThank you for your big interest in my finds. I kindly appreciate you for reporting the issue of strings having special characters in them. I am going to fix this later.