WSH Jscript AppActivate() and Sleep() - jscript

I'm trying to learn JScript (not javascript) but I'm having a hell of a time finding resources. What I want to do is manipulate the windows shell to create a program that manipulates other programs so I specifically need to be able to use Jscript's AppActivate() function to switch focus between windows however it doesn't work. I'm assuming it doesn't work because the calls to AppActivate are happening before the windows I'm trying to manipulate fully load?
Could someone please:
Give me a working example of switching between say, calculator and notepad, also give me some good reference material?
Also, how do I pause the program at the end of execution so I can read the errors in the command prompt?
This is what I wrote, and it crashes every time.
import System;
import System.Drawing;
import System.Windows.Forms;
import Accessibility;
//Open calculator, wait 3 seconds, open notepad, wait three seconds, change focus to calculator.
var WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run("calc");
WshShell.Sleep(3000);
WshShell.Run("c:/windows/system32/notepad.exe");
WshShell.Sleep(3000);
AppActivate("calc");

The first lines of your script (import ...) aren't WSH JScript. Delete them. The WScript.Shell object doesn't have a .Sleep method. That method is provided by the (global) WScript object. To use .AppActivate, you need to specify the WScript.Shell object.
Working code:
var WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run("calc");
WScript.Sleep(3000);
WshShell.Run("c:/windows/system32/notepad.exe");
WScript.Sleep(3000);
WshShell.AppActivate("calc");
To see what's going on, start your script from a console ('DOS box').
Start reading here.
Update wrt comments:
WSH JScript is not .NET JScript. A 'port' of the above script to .NET looks like:
import System;
var WshShell = new ActiveXObject("WScript.Shell");
WshShell.Run("calc");
System.Threading.Thread.Sleep(3000);
WshShell.Run("c:/windows/system32/notepad.exe");
System.Threading.Thread.Sleep(3000);
WshShell.AppActivate("calc");
System.Threading.Thread.Sleep(3000);
WshShell.AppActivate("notepad");
As you can see, you need to use the sleep feature of the platform (WSH vs .NET).

Related

Executing VB script from Spring Boot Application

I want to execute a VB script from Spring Boot application, the script is like:
' Creating a file as test acces to macro
Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.CreateTextFile("C:\excel\FLAG_TEST")
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\excel\excelFile.xls")
objExcel.Application.EnableEvents = False
objExcel.Application.DisplayAlerts = False
objExcel.Application.Run "excelFile.xls!executeMacroFunction"
objExcel.Application.Quit
I tried to execute the script from Spring Boot service by:
Runtime.getRuntime().exec(new String[]{"C:\\Windows\\System32\\wscript.exe", "C:/vb/script.vbs"});
The above line code does not work on the application deployed on Tomcat 9 (it works fine when running as Spring Boot App on Eclipse)
Then I tried to execute the script via a batch file launched from the app
On batch file, I tried to execute the VB script by
rem First way
Set wscript = CreateObject("WScript.Shell")
wscript.Run "C:/vb/script.vbs"
--------------------
rem Second way (System 64bit)
C:\Windows\System32\wscript.exe C:/vb/script.vbs
--------------------
rem Third way (System 64bit)
wscript C:/vb/script.vbs
And running the batch file from Java with different ways too:
// First way
ProcessBuilder processBuilder = new ProcessBuilder("C:/batch/executor.bat");
final Process process = processBuilder.start();
// Second way
Process process = Runtime.getRuntime().exec("cmd /c start \"\" C:/batch/executor.bat");
// Third way
Process process = Runtime.getRuntime().exec(
"cmd /c start \"\" C:/batch/executor.bat",
null,
new File("C:\\Windows\\SysWOW64"));
All these ways do not work, the scripts have no problem since they work when I run manually the batch file (by double click)
On the execution of the macro from Spring Boot, the test file (FLAG_TEST) is created and then the execution is blocked at the line:
Set objExcel = CreateObject("Excel.Application")
Am I missing something ?...Thanks a lot in advance !
Tried also with Jacob DLL to run the Macro inside the excel file, it also didn't work for me within a Tomcat server
I decided at the end to abandon any kind of external tool and do the thing within Spring Boot, parsing the Excel file via an Excel Java API and migrating the Macro program to Java: JExcel
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
Unlike some other Excel parsing APIs, the Jexcel get the cell text as it is: String, Number, Boolean, Formula (its displayed result), no need to handle the different cases of content type
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.WorkbookSettings;
// Set Encoding 1252 that supports many European languages (special characters included)
WorkbookSettings workbookSettings = new WorkbookSettings();
workbookSettings.setEncoding("Cp1252");
Workbook workbook = Workbook.getWorkbook(new File(EXCEL_FILE_LOCATION), workbookSettings);
Sheet sheet = workbook.getSheet(0);
Cell cellDemo = sheet.getCell(0, 0); // Or sheet.getCell("A1");
// Get the displayed cell centent as a text
String cellContent = cellDemo.getContents();
System.out.print("Cell A1 centent:" + cellContent);
The Java parsing makes the exception handling of data validation easier and more precise, no kind of abstract HMI error message (Error occurred wile processing the Excel file...)
Turns out that the Excel Java reading API implementation took less time than the several attempts of runing the Macro externally :D

Unable to use win32com constants to automate powerpoint

I am new to python, trying to automate powerpoint using win32com. I am unable to import or use constants in my scripts. I have ran makepy to create libraries. below is the error messages & script. Can someone tell me how to import constants ?
Script :
import win32com.client
Application =win32com.client.gencache.EnsureDispatch("PowerPoint.Application")
Presentation = Application.Presentations.Add()
Base = Presentation.Slides.Add(1, ppLayoutBlank)
Error messages :
Traceback (most recent call last):
File "ppt.py", line 14, in
Base = Presentation.Slides.Add(1, ppLayoutBlank)
NameError: name 'ppLayoutBlank' is not defined
The INTEROP method you have chosen depends on the application interface to which you are connecting.
Not defined usually means that there is no such variable, but Python more often raises NameError in such cases. So what is exactly happening here is a little unclear.
So, depends on the version of PPoint on how to communicate with it.
I advise you to use pywinauto instead and go for "brute_force", i.e. emulate key presses and/or clicks etc. on right buttons, menues etc.
Because the names of thous is little less likely to change trough out the versions than a COM interface.
Microsoft has a nasty habit of changing just a little bit the interface, and then a program stops working.
If you want to insist on win32com, you will have to read PPoint's documentation for a specific version (or Office version), and for win32com for your Python version.
You should see whether you should start a COM Client or is there some other MS tweak you need to employ.
I'm under Linux now and cannot test here, but try to
import win32com.client.constants
... and then look for the constants defined in that module.
See also How to use win32com.client.constants with MS Word?.

Using VBA to control another program entirely

I'm currently working on simplifying a process at work. It involves a Chatillon DFIS Force Meter which uses a serial connection to transmit data. The data gets sent to the Chattillon program as text and can only be saved as a .dat file. I'm trying to set up an Excel workbook that can just automatically open the program and have different commands to put the information straight into Excel. The Commands would involve changing the units, zeroing the sensor, and transmitting.
I've done some looking around and found that the Shell feature gives you access to opening the file and should help allow you to control it but I haven't found a way to call and manipulate the program through Excel.
Chatillon Program, basically buttons to click with a mouse
Excel and VBA can control external applications if they have a COM interface - that is to say, if you can declare the application as an object, create an instance of the object, and see its methods and attributes.
If you can possibly get hold of a COM wrapper for your program, do it that way.
If you can't... You won't enjoy doing it using I/O streams and a Windows Shell object, because command-line DOS interfaces aren't particularly friendly as a User Interface, and they are flakier than breakdancing in a pastry factory when you try to use them as an API in VBA.
Firstly, you need the 'WshShell' object exposed by the Windows Script Host Object Model. You can declare and instantiate it by late binding as shown:
Dim objWshell As Object
Set objWshell = CreateObject("WScript.Shell")
But the correct method (which will give you Intellisense drop-downs of the properties and methods) is to use the 'Tools:References...' dialog to create a reference to the parent library, which is usually found at C:\Windows\System32\wshom.ocx
You can then declare the Shell object as:
Dim objWshell As IWshRuntimeLibrary.WshShell
Set objWshell = New IWshRuntimeLibrary.WshShell
Running a command-line executable and reading the I/O streams in VBA:
This is an example that opens a command window and runs a command-line executable, feeding it a command-line switch '-s' and a parameter encapsulated in double quotes.
Note that the executable I'm running is NOT 'regsvr32.exe' - my shell object is executing cmd.exe, and that is the source and sink of the I/O streams.
You can, of course, run your application directly. It might work. But it is very common for the output stream to lock or 'hang' your calling function and its VBA thread when you call .StdOut.ReadLine or .StdOut.ReadAll - you have been warned.
With objWshell.Exec("CMD /K")
.StdIn.WriteBlankLines 3
.StdIn.WriteLine "C:"
.StdIn.WriteLine "CD C:\"
.StdIn.WriteLine "regsvr32.exe -s " & Chr(34) & "%LIBDIR%\FXPricer.dll" & Chr(34)
.StdIn.WriteBlankLines 1
Do Until .StdOut.AtEndOfStream
Debug.Print .StdOut.ReadLine
Loop
Do Until .StdErr.AtEndOfStream
Debug.Print .StdOut.ReadLine
Loop
.Terminate
End With
Share and Enjoy. And, as always, watch out for line breaks inserted by your browser (or by StackOverflow's textbox interface) in the source code samples.

Using JavaScript API commands in ActionScript file

I am new to actionscript and jsfl programming. I am using Adobe Flash Professional CS5.5 and windows 7 operating system. I am trying to execute Javascript API commands in my .as file using the MMExecute() function. When publishing the swf file the statements before and after the 'MMExecute' statement are getting executed but the Javascript command string I am using in the MMExecute function doesn't seem to get executed. I am using a basic JSFL command to just trace to the output window in flash. Also, I am publishing the swf file to the WindowsSwf folder present in the Configuration folder. The fla file I have is a blank file with nothing added to it and the code I am using is as follows.
import flash.display.*;
import flash.text.*;
import flash.external.*;
import adobe.utils.MMExecute;
var str:String=new String();
str='fl.trace("Working..");';
MMExecute(str);
Please help me out.
Thanks in advance.
I'm not a real JS programmer, just an artist who got into JSFL, but:
var str:String=new String();
seems odd to me. I don't typically declare var types in JSFL.
(no idea if that's common or I'm just sloppy.)
I would typically just write
var str='fl.trace("Working..");';
it is also possible you may need to escape the first semicolon.

Scriptom (groovy) leaves Excel process running - am I doing something wrong?

I am using the Scriptom extension to Groovy 1.7.0 to automate some processing using Excel 2007 under Windows XP.
This always seems to leave an Excel process running despite my calling quit on the excel activeX object. (There is a passing reference to this phenomenon in the Scriptom example documentation too.)
Code looks like:
import org.codehaus.groovy.scriptom.ActiveXObject;
def xls = new ActiveXObject("Excel.Application")
xls.Visible = true
// do xls stuff
xls.Quit()
The visible excel window does disappear but an EXCEL process is left in the task manager (and more processes pile up with each run of the script).
There are no error message or exceptions.
Can anyone explain why the Excel process is left behind and is there any way to prevent it from happening?
This works:
xls.Quit()
Scriptom.releaseApartment()
The javadocs state:
In some cases, the JVM can close
before everything is cleaned up, which
can leave automation servers
(especially Excel) hanging. Call this
before your script exits to get
correct behavior from automation
servers.
Looks like you are missing
xls.release();
like it is done here.

Resources