Tuesday, April 6, 2010

Guide: How to automate Windows applications

Guide: How to automate Windows applications: "

The first part of this tutorial explained how AutoIt can help you to automate tasks by simulating keypresses. But while this is a powerful technique that enables you to control just about any application, it does have its problems.

The scripting code quickly becomes cryptic; there's no way to tell what a keypress sequence does without looking at the app. It's not always reliable, either – a simple interface change can break your keypress sequence and force you to start again.

However, there's a smarter automation alternative out there called the Component Object Model (COM). Some apps use it to make their functionality available to other scripts and programs, including Windows, Microsoft Office, Skype and many others. Using it you can send emails in Outlook, automate Skype calls, create spreadsheets and more.

Getting started

The first step in using COM is to create a variable that refers to the application object we need (or create an instance of the object, in programmer-speak). In AutoIt, that looks something like this:

$oShell = ObjCreate('Shell. Application')

The 'sign tells us that this is a variable called '$oShell'. We use a lower-case 'o' as the first letter of the variable name to reminds us that this is an object. We then ask the ObjCreate function to create a 'Shell.Application' object. This is a copy of Explorer that gives us instant access to lots of useful Windows features.

desktop

The easiest way to make use of an object is to apply one of its methods. These are commands that the object makes available. Our Shell.Application object, for instance, has a method called 'MinimizeAll' that will minimise all open application windows so we can see the desktop. We can use it by applying that method name to the variable we've just created, like this:

$oShell. MinimizeAll.

Similarly, we can use $oShell.UndoMinimizeAll to undo the minimise command, restoring application windows to their previous positions. We can also rearrange windows by appending TileHorizontally, TileVertically or alternatively CascadeWindows.

Our Shell.Application object provides plenty of handy shortcuts, too. If we want to launch the Search window, for instance, then we can use this:

$oShell.FindFiles.

Then there's the 'FileRun' method, which launches the Run box; 'SetTime', which opens the Date and Time dialog; and 'ControlPanelItem', which displays an applet that you specify. For example, typing ControlPanel Item('Inetcpl.cpl') will launch the Internet Options dialog.

microsoft help

Need some more? Check out the official Microsoft Shell.Application documentation for the full list of methods here.

Controlling services

We've started gently with some of the simpler Shell.Application options, but the object provides plenty of more interesting features for us to explore.

The 'AddToRecent' method, for instance, will add the document you specify to the Windows Recent Files list. Use it like this (ensuring that 'c:\file.ext' is replaced with the path of a real file on your PC):

$oShell = ObjCreate(FShell.Application') $oShell.AddToRecent('c:\file.ext')

By adding more file names, you could customise a script like this to ensure that the Recent Files list always includes a particular set of commonly used documents.

Alternatively, you could protect your privacy by creating a script that replaces the Recent Files list with your choice of files, so nobody can use it to keep an eye on what you've been doing. The ability to stop and start Windows services introduces more interesting possibilities.

You could create a script to close down non-essential services to save resources before you run a demanding game, for instance, and another that will start them again afterwards. Here are a couple of short examples of this:

StopServices.au3
$oShell = ObjCreate('Shell. Application')
$oShell.ServiceStop('wuaserv', false)
$oShell.ServiceStop('wsearch', false)
StartServices.au3
$oShell = ObjCreate('Shell. Application')
$oShell.ServiceStart('wuaserv', false)
$oShell.ServiceStart('wsearch', false)

Here the 'StopServices.au3' script begins by creating a Shell.Application object, then uses the 'ServiceStop' method to stop the 'wuaserv' (Windows Update) and 'wsearch' (Windows Search) services. The second ServiceStop value tells Windows whether you want this change to be permanent. Set it to 'true' and Windows will disable the service, so it won't start when you next reboot.

However, as the Search and Windows Update services are important, we only want to turn them off temporarily, so we should set the second value to false. Run this script first to free up RAM and system resources, then launch your hungry app. When you're done, run the StartServices script and it'll reverse the process, using the ServiceStart method to relaunch services that were closed.

If you forget to run StartServices, don't worry – any services you've paused will be started again the next time you reboot. To make this really useful we could expand it to include other non-essential services. Candidates for this include Spooler (the print spooler), BITS (Background Intelligent Transfer Service), EMDMgmt (ReadyBoost) and third-party services such as Apple Mobile Device (only necessary when you're connecting an iPod or iPhone to your PC).

services

To explore this further, run services.msc to view the services that are active on your PC. Find a service that you think is nonessential and could be turned off safely for a while. Double-click it and note the service name. Disabling a critical service could disable your PC, so check at www.blackviper.com to confirm that a service is safe to turn off temporarily.

If it is, add $oShell.ServiceStop('W32Time', false) to StopServices.au3 and $oShell. ServiceStart('W32Time', false) to StartServices.au3.

Automating Word

If you've got a copy of Word installed, you can automate the creation of a Word document with a script along these lines:

$oWord = ObjCreate('Word. Application')
$oWord.Documents.Add
$oWord.Selection.TypeText('Some words go here')
$oWord.ActiveDocument. SaveAs('c:\autoitcreatedme.doc')
$oWord.Quit

Here we've created a 'Word. Application' object (essentially loading an instance of Word) and added to its collection of documents (you could have several open at once, but this just creates the first).

The 'Selection' property corresponds to the current insert point, where the cursor would be if you'd opened the document manually, and the 'TypeText' method enters some text there. Finally we save our work to a specified path and use the 'Quit' method to close the object.

The last step isn't strictly necessary when it's the end of the script, but if we were carrying on then it would be a good idea. A Word.Application object takes up a sizeable amount of RAM, and it's worth freeing that up as soon as you can.

Word

You can extend scripts like this in many different ways. Open a document instead of creating one by replacing '$oWord.Documents.Add' with $oWord.Documents.Open('c:\filename.doc'*.

Style the text in your document by setting the font name – add $oWord.Selection.Font.Name = 'Arial' – and size – use $oWord. Selection.Font.Size = '24'. Add the line $oWord.PrintOut() before the final 'Quit' and it'll send your work to the printer too.

Using Outlook Microsoft

Outlook provides a powerful COM object that presents all kinds of automation possibilities. Perhaps the most useful of these is the ability to send an email from a script. Here's an example:

$oOutlook = ObjCreate('Outlook. Application')
$oMsg = $oOutlook.CreateItem(0)
$oMsg.To = 'persons.name@ domain.com'
$oMsg.Subject = 'COM test'
$oMsg.Body = 'important content goes here'
$oMsg.Send

Our script starts by creating an 'Outlook.Application' object. This will usually load Outlook if it's not running already, but it may not always work. Launch Outlook before running the script if you get errors. The script then uses '$oOutlook' to create a further object and '$oMsg' to create a new message before setting its recipient, subject and body.

We could have set a CC address using $oMsg.CC = 'you@youraddress.com' or the sender's address with $oMsg.SenderEmailAddress = me@myisp.com, but simpler is better right now.

We finish with the 'Send' method, which sets our message on its way. At least, that's the plan. In practice, you'll probably find that Outlook pops up a message complaining that a program is trying to access it to send emails. This is a security feature that's designed to stop malware using your PC to send spam, but unfortunately it'll block your legitimate script too.

warning

If you'd like to be able to send emails from a script then the best solution is to install Advanced Security for Outlook. This clever tool detects programs trying to access Outlook and gives you the option to block them if they're unexpected or run them without warnings if you're sure they're legitimate. It works on every version of Windows from 95 to 7, and every version of Outlook from 2000 to 2010. Best of all, it's free.

Going further

If you're interested in using COM to automate functions and would like to create more advanced scripts, you'll need to learn more about COM and the individual objects that different applications make available. The simplest way to go about this is to open the AutoIt Help file. Click the Contents tab and select 'Obj/COM Reference' to find a quick COM primer with some handy examples, including one on automating Excel functions.

If you expand the Word Management folder, you'll find information on some functions bundled with AutoIt that let you automate Word. Look at the example for '_Word DocAddPicture', for instance, to see how you can create a Word document from an AutoIt script and then add some pictures to it.

The AutoIt forum is another essential source of help. If you have a question, it's probably been asked before, so the Search tool should reveal a variety of useful answers. If you're lucky, someone may have already uploaded a script that does what you want in the Example Scripts section of the forum. Be sure to search the forum before you start writing something – you could save yourself a lot of time.

If you're feeling really ambitious then you could browse Microsoft's own documentation. Its pages on the Shell.Application object don't use AutoIt examples, but you'll get more details on the various methods the object makes available and how they should be used.

Alternatively, if you don't have much use for COM then you could simply wait until the next issue of PC Plus for the third and final part of this tutorial series. We'll be combining everything we've learned so far, giving our scripts an interface so that they can communicate with the user, adding some low-level tricks and showing how the leading AutoIt scripts can compete with the best that any other programming language has to offer.



"



(Via TechRadar: All latest feeds.)

No comments: