Thursday, May 24, 2007

Launching Apps and Printing Docs with the Windows Shell

A reader recently asked how to launch an application from within a Ruby script. A quick answer is to use the system or exec methods. But you can also leverage the Windows Shell to launch applications, and have control over the window state. You can also use the shell to print documents. Let's get right down to it, shall we?...

Require the win32ole library...


require 'win32ole'

Create an instance of the Windows Shell object...

shell = WIN32OLE.new('Shell.Application')

The shell object's ShellExecute method performs a specified operation on a specified file. The syntax is...

shell.ShellExecute(FILE, ARGUMENTS, DIRECTORY, OPERATION, SHOW)

FILE: Required. String that contains the name of the file on which ShellExecute will perform the action specified by OPERATION.

ARGUMENTS: Optional. The parameter values for the operation.

DIRECTORY: Optional. The fully qualified path of the directory that contains the file specified by FILE. If this parameter is not specified, the current working directory is used.

OPERATION: Specifies the operation to be performed. It should be set to one of the verb strings that is supported by the file (Examples: 'open', 'edit', or 'print'). If this parameter is not specified, the default operation is performed.

SHOW: Recommends how the window that belongs to the application that performs the operation should be displayed initially (0 = hidden, 1 = normal, 2 = minimized, 3 = maximized). The application can ignore this recommendation. If this parameter is not specified, the application uses its default value.

So, to launch Excel in a maximized window...

shell.ShellExecute('excel.exe', '', '', 'open', 3)

I suppose you could also launch your rails app with something like this...

shell.ShellExecute('ruby.exe', 'c:\my_rails_app\script\server', '', 'open', 1)

To print a document, hiding the application window...

shell.ShellExecute('C:\MyFolder\Document.txt', '', '', 'print', 0)

That's about it. As always, post a comment here or send me email if you have questions, comments, or would like to request a topic for discussion.

Thanks for stopping by!

2 comments:

Maxim said...

Thanks for useful tips

Gagan said...

Thanks for the above information
I am facing a problem that i guess u might help i.e,
i need to execute two exe one after the another,when the previous exe is executed in the local system the other one should follow.

I know its quite difficult to achieve but i think u could solve it.

thanks
waiting for a positive response