COM

Commands for accessing COM servers

SYNOPSIS

package require twapi
clsid_to_progid CLSID
comobj PROGID_OR_CLSID ?options?
COMOBJ NAME ?parameter ...?
COMOBJ -bind SCRIPT
COMOBJ -call METHOD ?parameter ...?
COMOBJ -default
COMOBJ -destroy
COMOBJ -get PROPERTY ?parameter ...?
COMOBJ -interface
COMOBJ -isnull
COMOBJ -iterate VARNAME SCRIPT
COMOBJ -print
COMOBJ -set PROPERTY VALUE ?parameter ...?
COMOBJ -unbind BINDID
COMOBJ -with METHODLIST ?parameters ...?
comobj_object DISPLAYNAME ?-interface IDispatch|IDispatchEx?
get_typelib_path_from_guid GUID MAJOR MINOR ?-lcid LCID?
iid_to_name IID
ITypeLibProxy_from_path PATH ?-registration REGOPT?
ITypeLibProxy_from_guid GUID MAJOR MINOR ?-lcid LCID?
name_to_iid INTERFACENAME
progid_to_clsid PROGID
timelist_to_variant_time TIMELIST
unregister_typelib GUID MAJOR MINOR ?-lcid LCID?
variant_time_to_timelist DOUBLE

DESCRIPTION

This module provides commands for supporting COM clients. TWAPI's COM support is limited to client side calls only and does not provide facilities for writing COM components. Like other scripting languages like VBScript and Javascript, TWAPI's COM support is focused on Automation objects through their IDispatch and IDispatchEx interfaces. This provides the ability to script Windows applications such as Microsoft Office and Internet Explorer as well as admistrative interfaces such as Active Directory and Windows Management Instrumentation.

This documentation assumes some familiarity with COM programming concepts such as COM interfaces, COM automation, PROGID and CLSID identifier types etc.

COM API layers

TWAPI's COM support is implemented in layers:

  • At the lowest layer, TWAPI supports the raw Windows API calls such as IUnknown_QueryInterface or IDispatch_Invoke. It is not expected that applications will directly use these calls and they are not documented here. See the Windows Platform SDK for details of these calls.
  • At the next layer, TWAPI provides object wrappers around COM interfaces like IUnknown, IDispatch, ITypeInfo etc. They provide a more convenient programming interface as well as better efficiency by caching type information etc. They also provide access to type libraries and other system facilities.
  • The highest layer exposes COM automation servers through "proxy" objects created through the comobj command. All details of method lookup, type management and runtime dispatching are internally handled. The COM automation server's methods and properties are directly accessible to the application. In the rest of this documentation the proxy object and underlying COM automation object are both refered to as "object" unless the distinction is significant.

Creation and Destruction of COM automation objects

A COM automation proxy object is created through the command comobj using the PROGID or CLSID of the corresponding COM class. This returns a Tcl object command that may be used to access the object's methods and properties. The example below creates a proxy object using the PROGID for Internet Explorer.

set ie [comobj InternetExplorer.Application -enableaaa]

Alternatively, the comobj_object command can be used to bind to a COM object identified by its display name. For example, the following creates a COM object for an Excel file.

set xlso [comobj_object c:\\data\\myspreadsheet.xls]

When an object is no longer required, it must be explicitly destroyed by calling the command with the -destroy subcommand.

Accessing Properties and Methods of Automation Objects

The properties and methods of a COM object can be accessed through the proxy object returned by the comobj command. The following sequence of commands shows a sample session that drives Internet Explorer through its properties and methods.

Start up Internet Explorer (note it will not be visible yet)

set ie [comobj InternetExplorer.Application -enableaaa]

Automation objects can be associated with a default property that is retrieved if no property or method are specified. This is the property marked as the default value in the COM object's IDL definition. In TWAPI this default property can be accessed using the -default method on the object.

$ie -default

Properties can be directly retrieved and modified. For example, the following commands makes its window visible by changing its Visible property.

$ie Visible true

In theory, the names of properties and methods of an automation object can overlap. Althouth TWAPI can usually figure out whether a property is being retrieved/set or a method is being called, you can explicitly control this by using the -get, -set or -call subcommands followed by the actual name. So the above call could also have been written as

$ie -set Visible true

to explicitly indicate we want to set the property called Visible as opposed to making a call to the COM object's method of the same name (if there was one).

To go to the TWAPI home page, invoke the Navigate method

$ie Navigate http://twapi.sf.net

Again, we could specify this is a method call, not a property, by explicitly indicating that as follows:

$ie -call Navigate http://twapi.sf.net

Explicitly specifying -call may also be required to disambiguate between methods that are implemented within the TWAPI comobj command object and the actual COM automation object itself. For example, the method destroy destroys the command object. If the underlying automatio object also had a destroy method, you would need to invoke it as

$ie -call destroy

To continue with the example, we can read the LocationURL property to find the URL after redirection

$ie LocationURL

Ask the application to exit by calling its Quit method.

$ie Quit

Finally, destroy the proxy object and release the underlying COM object,

$ie destroy

COM Collections

Some COM objects are collection of items which may even be other COM objects. The items within these collections can be accessed by their index (which is not necessarily an integer) using the Item method as shown below.

set fso [comobj Scripting.FileSystemObject]
set drives [$fso Drives]
set cdrive [$drives Item c:]
puts "Drive C: is [lindex {{not ready} ready} [$cdrive IsReady]]"
$cdrive -destroy
$drives -destroy
$fso -destroy

In the above example, the Drives method of the Scripting.FileSystemObject object (implemented as an automation object by the Windows Shell) returns a collection drives. The drive letter c: is used to index into the collection object drives. As an alternative to explicit indexing in this fashion, TWAPI provides the -iterate method for iterating over all items in the collection. This is similar to the VBScript For each statement. The following example illustrates this.

set fso [comobj Scripting.FileSystemObject]
set drives [$fso Drives]
$drives -iterate drive {
    set drive_letter [$drive DriveLetter]
    if {[$drive IsReady]} {
        puts "Drive $drive_letter free space: [$drive FreeSpace]"
    } else {
        puts "Drive $drive_letter is not ready."
    }
    $drive -destroy
}
$drives -destroy
$fso -destroy

The -iterate operator on the collection then loops through each item in the collection, assigning the item to drive. In this case, each item is itself a COM automation object on which commands can be invoked. Note that the drive object generated in each iteration has to be explicitly destroyed.

Navigating Automation Objects

In many cases, the resource represented by a COM object has to be accessed by navigating through multiple intermediary objects. For example, the following example sets all cells within a range in a spreadsheet to 12345.

set xl [comobj Excel.Application]
$xl Visible true
set workbooks [$xl Workbooks]
set workbook [$workbooks Add]
set sheets [$workbook Sheets]
set sheet [$sheets Item 1]
set cells [$sheet range a1 c3]
$cells Value 12345
$cells -destroy
$sheet -destroy
$sheets -destroy
$workbook -destroy
$workbooks -destroy
$xl Quit
$xl -destroy

In the above example, in order to get to the range we have to navigate through a hierarchy of objects, starting with the application, the workbook collection, a workbook within the collection, the worksheets collection, a worksheet within that collection and finally the cell range. After setting the value, all the created objects have to be deleted.

As an alternative, TWAPI automation proxy objects provide the -with internal method to simplify this process:

set xl [comobj Excel.Application]
$xl Visible true
$xl -with {
    Workbooks
    Add
    Sheets
    {Item 1}
    {range a1 c3}
} Value 12345
$xl -destroy

The -with method takes a list of intermediate methods and associated parameters each of which should return a new object. Each method in the method list is invoked on the object returned by the previous method and should itself return a new object. The final object created from this list is passed the remaining arguments in the command. All intermediate objects are automatically destroyed.

COM Events

Some COM objects may generate notifications when certain events occur. A callback script may be registered using the -bind subcommand on a COMOBJ object. This script is invoked for every notification event generated by the COM object. The event name and parameters provided by the COM event source are appended to the script.

The following example receives events from Internet Explorer and prints them.

proc print_event args {puts "Received: [join $args ,]"}
set ie [comobj InternetExplorer.Application -enableaaa]
$ie Visible true
set bind_id [$ie -bind print_event]
$ie Navigate http://www.tcl.tk
after 2000
$ie -unbind $bind_id
$ie Quit
$ie -destroy

Note that the script is unregistered using the -unbind subcommand when no longer needed.

Interface Wrappers

In addition to the high level comobj based access to COM automation objects, TWAPI also provides object based wrappers for certain standard COM interfaces. These are provided for finer control of COM operation when the high level comobj does not provide enough flexibility. These wrapped include IUnknown, IDispatch, IDispatchEx, ITypeInfo, ITypeLib and ITypeComp. The corresponding wrapper classes are named with a Proxy suffix. For example, IUnknown is wrapped by the class IUnknownProxy.

Use of the classes requires a detailed understanding of COM programming techniques including lifetime management of objects through reference counting. Individual methods of these objects are not documented here. See the Windows SDK for details on these.

In addition to the standard methods defined by these interfaces, the proxy wrappers also implement additional helper methods that simplify working with the interfaces.

The following illustrates how these wrappers might be used:

set tlib [get_itypelib c:/windows/system32/stdole2.tlb]
set count [$tlib GetTypeInfoCount]
for {set i 0} {$i < $count} {incr i} {
    if {[$tlib GetTypeInfoType $i] == 4} {
        puts [lindex [$tlib GetDocumentation $i] 0]
    }
}
$tlib Release

The example starts off by getting a ITypeLibProxy object which wraps the ITypeLib interface for the stdole2.tlb type library. It then iterates through to print the names of dispatch interfaces in the type library using the ITypeLib methods GetTypeInfoCount, GetTypeInfoType and GetDocumentation as documented in the Windows SDK.

Note the object is released by calling Release and not its destroy method. This follows standard COM methodology. Calling the destroy method will delete the object while there might still be other references to it.

The same may be written with the @Foreach helper method as follows:

set tlib [get_itypelib c:/windows/system32/stdole2.tlb]
$tlib @Foreach -type dispatch ti {
    puts [$ti @GetName]
    $ti Release
}
$tlib Release

The @Foreach method passes ITypeInfoProxy objects into the loop for every dispatch interface type entry in the library.

Commands

clsid_to_progid CLSID
Returns the PROGID for a given CLSID. For example,
(tclsh) 53 % clsid_to_progid "{0002DF01-0000-0000-C000-000000000046}"
InternetExplorer.Application.1
comobj PROGID_OR_CLSID ?options?
Creates a COM object and returns a proxy object that can be used to access it. PROGID_OR_CLSID is either the PROGID or the CLSID for the COM object.

The returned value COMOBJ is itself a Tcl command object that can be used to access the COM object. When the object is no longer required it should be deleted by calling the command with the -destroy subcommand. You should not delete the command simply by calling the Tcl rename command as this will lead to memory and resource leaks. options may contain one or more of the options in the table below. Refer to the CLSCTX documentation in the Windows SDK for details regarding these options.
-disablelog BOOLEAN If specified as true, disables logging of failures. Corresponds to the flag CLSCTX_NO_FAILURE_LOG in the SDK.
-download BOOLEAN If specified as true, allows downloading of code from the Internet or Directory Service. This corresponds to setting the flag CLSCTX_ENABLE_CODE_DOWNLOAD. If specified as false, disallows downloading of code from the Internet or Directory Service. This corresponds to setting the flag CLSCTX_DISABLE_CODE_DOWNLOAD.

If this option is not specified, neither of the flags is set in the underlying call to CoCreateInstance.
-enableaaa BOOLEAN If specified as true, enables activate-as-activator activations where a server process is launched under the caller's identity. This corresponds to setting the flag CLSCTX_ENABLE_AAA. If specified as false, disables activate-as-activator activations. This corresponds to setting the flag CLSCTX_DISABLE_AAA.

If this option is not specified, neither of the flags is set in the underlying call to CoCreateInstance.
-interface IDISPATCHINTERFACE By default, the command will bind to the object's IDispatch interface. If the object is known to support the IDispatchEx interface as well, this option may be used to specify that should be used instead. IDISPATCHINTERFACE must be IDispatch or IDispatchEx.
-model MODELLIST Specifies which of the COM hosting models are acceptable. MODELLIST must be a list containing one or more of the symbols localserver, remoteserver, inprocserver, inprochandler, or any signifying any model is acceptable.
-nocustommarshal BOOLEAN If true, the object creation will fail if it uses custom marshalling. Corresponds to the flag CLSCTX_NO_CUSTOM_MARSHAL.
COMOBJ NAME ?parameter ...?
The command interprets NAME as a property or method name of the COM object. In case of ambiguity (the object has read and write properties or a method of the same name), the command is interpreted as a property get if no additional parameters are specified, as a property put if exactly one additional parameters is specified and a method invocation otherwise.
COMOBJ -bind SCRIPT
Registers SCRIPT as a script to be invoked in the global scope whenever COMOBJ generates an event notification. The name of the event and any additional parameters in the notification are appended to the script.

The command returns an id. This id must be passed to the -unbind subcommand to unregister the script.

The binding is automatically deleted when COMOBJ is destroyed or may be removed explicitly through the -unbind subcommand.

See COM Events for an example.
COMOBJ -call METHOD ?parameter ...?
Calls the specified COM object method with the given parameters and returns the result if any.
COMOBJ -default
Returns the default property of the COM object.
COMOBJ -destroy
Destroys the COM object, removing any bindings and releasing resources.
COMOBJ -get PROPERTY ?parameter ...?
Returns the value of the specified property. Optional parameters may be specified if the property is an indexed property.
COMOBJ -interface
Returns the internal IDispatch pointer. Used for debugging purposes.
COMOBJ -isnull
Returns true if the object is a NULL COM object, false otherwise. This corresponds to a NULL IDispatch pointer that might be returned in some COM operations, for example, to indicate the end of a collection.
COMOBJ -iterate VARNAME SCRIPT
Iterates over items in COMOBJ which must be a COM collection. In each iteration, SCRIPT is executed in the caller's context with VARNAME being set to the value of the current item.

Note that if the item is itself a COM object, VARNAME will contain the name of a TCL command corresponding to that object and must be destroyed when no longer needed (not necessarily within SCRIPT).

See COM Collections for an example.
COMOBJ -print
Prints to stdout the methods and properties of the object. Used for debugging.
COMOBJ -set PROPERTY VALUE ?parameter ...?
Sets the value of the specified property. The optional parameters may be specified if the property is an indexed property.
COMOBJ -unbind BINDID
Deletes the COM event binding identified by BINDID.
COMOBJ -with METHODLIST ?parameters ...?
The -with subcommand takes a list of intermediate methods and associated parameters. Each element of this list should itself be a list the first element being the method or property name and remaining elements being the parameters to pass when that method/property is invoked. The method or property should return a new object and the next element in the list is invoked on the previously returned object. The final object created from this list is passed the remaining arguments in the command.

All the intermediate objects created are automatically destroyed.

See Navigating Objects for an example.
comobj_object DISPLAYNAME ?-interface IDispatch|IDispatchEx?
Creates a COM object identified by its display name DISPLAYNAME and returns a proxy object that can be used to access it. See comobj for more details.

By default, the command will bind to the object's IDispatch interface. If the object is known to support the IDispatchEx interface as well, the -interface option may be used to specify that should be used instead.
get_typelib_path_from_guid GUID MAJOR MINOR ?-lcid LCID?
Returns the path to the type library identified by GUID that is registered with the system. MAJOR and MINOR specify the version of the libary. An optional LCID may also be specified.
iid_to_name IID
Returns the name for the interface identifier IID (a GUID).
ITypeLibProxy_from_path PATH ?-registration REGOPT?
Reads a type library from the file at PATH and returns an ITypeLibProxy object for it. The type library is also optionally registered in the system registry. If -registration is not specified or specified as none, the type library is not registered. If REGOPT is register, the type library is registered. If REGOPT is default, the system's default rules for registration are followed.

The returned ITypeLibProxy object must be freed when done by calling its Release method.
ITypeLibProxy_from_guid GUID MAJOR MINOR ?-lcid LCID?
Returns an ITypeLibProxy object for a type library identified by GUID that is registered with the system. MAJOR and MINOR specify the version of the libary. An optional LCID may also be specified.

The returned ITypeLibProxy object must be freed when done by calling its Release method.
name_to_iid INTERFACENAME
Returns the unique interface identifier (IID) for the specified interface name, for example IDispatch.
progid_to_clsid PROGID
Returns the CLSID for a given PROGID. For example,
(wish) 51 % progid_to_clsid InternetExplorer.Application
{0002DF01-0000-0000-C000-000000000046}
timelist_to_variant_time TIMELIST
Several COM applications store date and time information as type double with the integral part representing the number of days since an epoch and the fractional part representing the time in the day. This command converts TIMELIST to this format. TIMELIST must be a list of 7 elements representing the year, month, day, hour, minutes, seconds and milliseconds.
unregister_typelib GUID MAJOR MINOR ?-lcid LCID?
Unregisters the type library identified by GUID with version MAJOR.MINOR from the system registry. An LCID may be optionally specified.
variant_time_to_timelist DOUBLE
Several COM applications store date and time information as type double with the integral part representing the number of days since an epoch and the fractional part representing the time in the day. This command takes such a time value and returns a list of 7 elements representing the year, month, day, hour, minutes, seconds and milliseconds.

COPYRIGHT

Copyright © 2006-2010 Ashok P. Nadkarni

Tcl Windows API 3.0.29 Privacy policy