Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

676 lines
22 KiB

  1. # The documentation is at the __END__
  2. package Win32::OLE;
  3. use strict;
  4. use vars qw($VERSION @ISA @EXPORT @EXPORT_OK @EXPORT_FAIL $AUTOLOAD
  5. $CP $LCID $Warn $LastError);
  6. $VERSION = '0.1005';
  7. use Carp;
  8. use Exporter;
  9. use DynaLoader;
  10. @ISA = qw(Exporter DynaLoader);
  11. @EXPORT = qw();
  12. @EXPORT_OK = qw(CP_ACP CP_OEMCP CP_MACCP CP_UTF7 CP_UTF8 in valof with OVERLOAD
  13. DISPATCH_METHOD DISPATCH_PROPERTYGET
  14. DISPATCH_PROPERTYPUT DISPATCH_PROPERTYPUTREF);
  15. @EXPORT_FAIL = qw(OVERLOAD);
  16. sub export_fail {
  17. shift;
  18. if ($_[0] eq 'OVERLOAD') {
  19. shift;
  20. eval <<'OVERLOAD';
  21. use overload '""' => \&valof,
  22. '0+' => \&valof,
  23. fallback => 1;
  24. OVERLOAD
  25. }
  26. return @_;
  27. }
  28. unless (defined &Dispatch) {
  29. # Use regular DynaLoader if XS part is not yet initialized
  30. bootstrap Win32::OLE;
  31. require Win32::OLE::Lite;
  32. }
  33. 1;
  34. ########################################################################
  35. __END__
  36. =head1 NAME
  37. Win32::OLE - OLE Automation extensions
  38. =head1 SYNOPSIS
  39. $ex = Win32::OLE->new('Excel.Application') or die "oops\n";
  40. $ex->Amethod("arg")->Bmethod->{'Property'} = "foo";
  41. $ex->Cmethod(undef,undef,$Arg3);
  42. $ex->Dmethod($RequiredArg1, {NamedArg1 => $Value1, NamedArg2 => $Value2});
  43. $wd = Win32::OLE->GetObject("D:\\Data\\Message.doc");
  44. $xl = Win32::OLE->GetActiveObject("Excel.Application");
  45. =head1 DESCRIPTION
  46. This module provides an interface to OLE Automation from Perl.
  47. OLE Automation brings VisualBasic like scripting capabilities and
  48. offers powerful extensibility and the ability to control many Win32
  49. applications from Perl scripts.
  50. The Win32::OLE module uses the IDispatch interface exclusively. It is
  51. not possible to access a custom OLE interface. OLE events and OCX's are
  52. currently not supported.
  53. =head2 Methods
  54. =over 8
  55. =item Win32::OLE->new(PROGID [, DESTRUCTOR])
  56. OLE Automation objects are created using the new() method, the second
  57. argument to which must be the OLE program id or class id of the
  58. application to create. Return value is undef if the attempt to create
  59. an OLE connection failed for some reason. The optional third argument
  60. specifies a DESTROY-like method. This can be either a CODE reference
  61. or a string containing an OLE method name. It can be used to cleanly
  62. terminate OLE objects in case the Perl program dies in the middle of
  63. OLE activity.
  64. The object returned by the new() method can be used to invoke
  65. methods or retrieve properties in the same fashion as described
  66. in the documentation for the particular OLE class (eg. Microsoft
  67. Excel documentation describes the object hierarchy along with the
  68. properties and methods exposed for OLE access).
  69. Optional parameters on method calls can be omitted by using C<undef>
  70. as a placeholder. A better way is to use named arguments, as the
  71. order of optional parameters may change in later versions of the OLE
  72. server application. Named parameters can be specified in a reference
  73. to a hash as the last parameter to a method call.
  74. Properties can be retrieved or set using hash syntax, while methods
  75. can be invoked with the usual perl method call syntax. The C<keys>
  76. and C<each> functions can be used to enumerate an object's properties.
  77. Beware that a property is not always writable or even readable (sometimes
  78. raising exceptions when read while being undefined).
  79. If a method or property returns an embedded OLE object, method
  80. and property access can be chained as shown in the examples below.
  81. =item Win32::OLE->GetActiveObject(CLASS)
  82. The GetActiveObject class method returns an OLE reference to a
  83. running instance of the specified OLE automation server. It returns
  84. C<undef> if the server is not currently active. It will croak if
  85. the class is not even registered.
  86. =item Win32::OLE->GetObject(MONIKER)
  87. The GetObject class method returns an OLE reference to the specified
  88. object. The object is specified by a pathname optionally followed by
  89. additional item subcomponent separated by exclamation marks '!'.
  90. =item Win32::OLE->Initialize(COINIT)
  91. The C<Initialize> class method can be used to specify an alternative
  92. apartment model for the Perl thread. It must be called before the
  93. first object is created. Valid values for COINIT are:
  94. Win32::OLE::COINIT_APARTMENTTHREADED - single threaded
  95. Win32::OLE::COINIT_MULTITHREADED - the default
  96. Win32::OLE::COINIT_OLEINITIALIZE - single threaded, additional OLE stuff
  97. COINIT_OLEINITIALIZE is sometimes needed when an OLE object uses
  98. additional OLE compound document technologies not available from the
  99. normal COM subsystem (for example MAPI.Session seems to require it).
  100. Both COINIT_OLEINITIALIZE and COINIT_APARTMENTTHREADED create a hidden
  101. top level window and a message queue for the Perl process. This may
  102. create problems with other application, because Perl normally doesn't
  103. process its message queue. This means programs using synchronous
  104. communication between applications (such as DDE initiation), may hang
  105. until Perl makes another OLE method call/property access or terminates.
  106. This applies to InstallShield setups and many things started to shell
  107. associations. Please try to utilize the C<Win32::OLE-E<gt>SpinMessageLoop>
  108. and C<Win32::OLE-E<gt>Uninitialize> methods if you can not use the default
  109. COINIT_MULTITHREADED model.
  110. =item OBJECT->Invoke(METHOD,ARGS)
  111. The C<Invoke> object method is an alternate way to invoke OLE
  112. methods. It is normally equivalent to C<$OBJECT->METHOD(@ARGS)>. This
  113. function must be used if the METHOD name contains characters not valid
  114. in a Perl variable name (like foreign language characters). It can
  115. also be used to invoke the default method of an object even if the
  116. default method has not been given a name in the type library. In this
  117. case use <undef> or C<''> as the method name. To invoke an OLE objects
  118. native C<Invoke> method (if such a thing exists), please use:
  119. $Object->Invoke('Invoke', @Args);
  120. =item Win32::OLE->LastError()
  121. The C<LastError> class method returns the last recorded OLE
  122. error. This is a dual value like the C<$!> variable: in a numeric
  123. context it returns the error number and in a string context it returns
  124. the error message.
  125. The last OLE error is automatically reset by a successful OLE
  126. call. The numeric value can also explicitly be set by a call (which will
  127. discard the string value):
  128. Win32::OLE->LastError(0);
  129. =item Win32::OLE->Option(OPTION)
  130. The C<Option> class method can be used to inspect and modify
  131. L<Module Options>. The single argument form retrieves the value of
  132. an option:
  133. my $CP = Win32::OLE->Option('CP');
  134. A single call can be used to set multiple options simultaneously:
  135. Win32::OLE->Option(CP => CP_ACP, Warn => 3);
  136. =item Win32::OLE->QueryObjectType(OBJECT)
  137. The C<QueryObjectType> class method returns a list of the type library
  138. name and the objects class name. In a scalar context it returns the
  139. class name only. It returns C<undef> when the type information is not
  140. available.
  141. =item OBJECT->SetProperty(NAME,ARGS,VALUE)
  142. The C<SetProperty> method allows to modify properties with arguments,
  143. which is not supported by the hash syntax. The hash form
  144. $Object->{Property} = $Value;
  145. is equivalent to
  146. $Object->SetProperty('Property', $Value);
  147. Arguments must be specified between the property name and the new value.
  148. It is not possible to use "named argument" syntax with this function
  149. because the new value must be the last argument to C<SetProperty>.
  150. This method hides any native OLE object method called C<SetProperty>.
  151. The native method will still be available through the C<Invoke> method:
  152. $Object->Invoke('SetProperty', @Args);
  153. =item Win32::OLE->SpinMessageLoop
  154. This class method retrieves all pending messages from the message queue
  155. and dispatches them to their respective window procedures. Calling this
  156. method is only necessary when not using the COINIT_MULTITHREADED model.
  157. All OLE method calls and property accesses automatically process the
  158. message queue.
  159. =item Win32::OLE->Uninitialize
  160. The C<Uninitialize> class method uninitializes the OLE subsystem. It
  161. also destroys the hidden top level window created by OLE for single
  162. threaded apartments. All OLE objects will become invalid after this call!
  163. It is possible to call the C<Initialize> class method again with a different
  164. apartment model after shutting down OLE with C<Uninitialize>.
  165. =back
  166. Whenever Perl does not find a method name in the Win32::OLE package it
  167. is automatically used as the name of an OLE method and this method call
  168. is dispatched to the OLE server.
  169. There is one special hack built into the module: If a method or property
  170. name could not be resolved with the OLE object, then the default method
  171. of the object is called with the method name as its first parameter. So
  172. my $Sheet = $Worksheets->Table1;
  173. or
  174. my $Sheet = $Worksheets->{Table1};
  175. is resolved as
  176. my $Sheet = $Worksheet->Item('Table1');
  177. provided that the C<$Worksheets> object doesnot have a C<Table1> method
  178. or property. This hack has been introduced to call the default method
  179. of collections which did not name the method in their type library. The
  180. recommended way to call the "unnamed" default method is:
  181. my $Sheet = $Worksheets->Invoke('', 'Table1');
  182. This special hack is disabled under C<use strict 'subs';>.
  183. =head2 Functions
  184. The following functions are not exported by default.
  185. =over 8
  186. =item in(COLLECTION)
  187. If COLLECTION is an OLE collection object then C<in $COLLECTION>
  188. returns a list of all members of the collection. This is a shortcut
  189. for C<Win32::OLE::Enum->All($COLLECTION)>. It is most commonly used in
  190. a C<foreach> loop:
  191. foreach my $value (in $collection) {
  192. # do something with $value here
  193. }
  194. =item valof(OBJECT)
  195. Normal assignment of Perl OLE objects creates just another reference
  196. to the OLE object. The C<valof> function explictly dereferences the
  197. object (through the default method) and returns the value of the object.
  198. my $RefOf = $Object;
  199. my $ValOf = valof $Object;
  200. $Object->{Value} = $NewValue;
  201. Now C<$ValOf> still contains the old value wheras C<$RefOf> would
  202. resolve to the C<$NewValue> because it is still a reference to
  203. C<$Object>.
  204. The C<valof> function can also be used to convert Win32::OLE::Variant
  205. objects to Perl values.
  206. =item with(OBJECT, PROPERTYNAME => VALUE, ...)
  207. This function provides a concise way to set the values of multiple
  208. properties of an object. It iterates over its arguments doing
  209. C<$OBJECT->{PROPERTYNAME} = $VALUE> on each trailing pair.
  210. =back
  211. =head2 Overloading
  212. The Win32::OLE objects can be overloaded to automatically convert to
  213. their values whenever they are used in a bool, numeric or string
  214. context. This is not enabled by default. You have to request it
  215. through the C<OVERLOAD> pseudoexport:
  216. use Win32::OLE qw(in valof with OVERLOAD);
  217. You can still get the original string representation of an object
  218. (C<Win32::OLE=0xDEADBEEF>), e.g. for debugging, by using the
  219. C<overload::StrVal> method:
  220. print overload::StrVal($object), "\n";
  221. Please note that C<OVERLOAD> is a global setting. If any module enables
  222. Win32::OLE overloading then it's active everywhere.
  223. =head2 Module Options
  224. The following module options can be accessed and modified with the
  225. C<Win32::OLE->Option> class method. In earlier versions of the Win32::OLE
  226. module these options were manipulated directly as class variables. This
  227. practice is now deprecated.
  228. =over 8
  229. =item CP
  230. This variable is used to determine the codepage used by all
  231. translations between Perl strings and Unicode strings used by the OLE
  232. interface. The default value is CP_ACP, which is the default ANSI
  233. codepage. Other possible values are CP_OEMCP, CP_MACCP, CP_UTF7 and
  234. CP_UTF8. These constants are not exported by default.
  235. =item LCID
  236. This variable controls the locale idnetifier used for all OLE calls.
  237. It is set to LOCALE_NEUTRAL by default. Please check the
  238. L<Win32::OLE::NLS> module for other locale related information.
  239. =item Warn
  240. This variable determines the behavior of the Win32::OLE module when
  241. an error happens. Valid values are:
  242. 0 Ignore error, return undef
  243. 1 Carp::carp if $^W is set (-w option)
  244. 2 always Carp::carp
  245. 3 Carp::croak
  246. The error number and message (without Carp line/module info) are
  247. available through the C<Win32::OLE->LastError> class method.
  248. =back
  249. =head1 EXAMPLES
  250. Here is a simple Microsoft Excel application.
  251. use Win32::OLE;
  252. # use existing instance if Excel is already running
  253. eval {$ex = Win32::OLE->GetActiveObject('Excel.Application')};
  254. die "Excel not installed" if $@;
  255. unless (defined $ex) {
  256. $ex = Win32::OLE->new('Excel.Application', sub {$_[0]->Quit;})
  257. or die "Oops, cannot start Excel";
  258. }
  259. # open an existing workbook
  260. $book = $ex->Workbooks->Open( 'test.xls' );
  261. # write to a particular cell
  262. $sheet = $book->Worksheets(1);
  263. $sheet->Cells(1,1)->{Value} = "foo";
  264. # write a 2 rows by 3 columns range
  265. $sheet->Range("A8:C9")->{Value} = [[ undef, 'Xyzzy', 'Plugh' ],
  266. [ 42, 'Perl', 3.1415 ]];
  267. # print "XyzzyPerl"
  268. $array = $sheet->Range("A8:B9")->{Value};
  269. print $array[0][1] . $array[1][1];
  270. # save and exit
  271. $book->Save;
  272. undef $book;
  273. undef $ex;
  274. Please note the destructor specified on the Win32::OLE->new method. It ensures
  275. that Excel will shutdown properly even if the Perl program dies. Otherwise
  276. there could be a process leak if your application dies after having opened
  277. an OLE instance of Excel. It is the responsibility of the module user to
  278. make sure that all OLE objects are cleaned up properly!
  279. Here is an example of using Variant data types.
  280. use Win32::OLE;
  281. $ex = Win32::OLE->new('Excel.Application', \&OleQuit) or die "oops\n";
  282. $ex->{Visible} = 1;
  283. $ex->Workbooks->Add;
  284. $ovR8 = Variant(VT_R8, "3 is a good number");
  285. $ex->Range("A1")->{Value} = $ovR8;
  286. $ex->Range("A2")->{Value} = Variant(VT_DATE, 'Jan 1,1970');
  287. sub OleQuit {
  288. my $self = shift;
  289. $self->Quit;
  290. }
  291. The above will put value "3" in cell A1 rather than the string
  292. "3 is a good number". Cell A2 will contain the date.
  293. Similarly, to invoke a method with some binary data, you can
  294. do the following:
  295. $obj->Method( Variant(VT_UI1, "foo\000b\001a\002r") );
  296. Here is a wrapper class that basically delegates everything but
  297. new() and DESTROY(). The wrapper class shown here is another way to
  298. properly shut down connections if your application is liable to die
  299. without proper cleanup. Your own wrappers will probably do something
  300. more specific to the particular OLE object you may be dealing with,
  301. like overriding the methods that you may wish to enhance with your
  302. own.
  303. package Excel;
  304. use Win32::OLE;
  305. sub new {
  306. my $s = {};
  307. if ($s->{Ex} = Win32::OLE->new('Excel.Application')) {
  308. return bless $s, shift;
  309. }
  310. return undef;
  311. }
  312. sub DESTROY {
  313. my $s = shift;
  314. if (exists $s->{Ex}) {
  315. print "# closing connection\n";
  316. $s->{Ex}->Quit;
  317. return undef;
  318. }
  319. }
  320. sub AUTOLOAD {
  321. my $s = shift;
  322. $AUTOLOAD =~ s/^.*:://;
  323. $s->{Ex}->$AUTOLOAD(@_);
  324. }
  325. 1;
  326. The above module can be used just like Win32::OLE, except that
  327. it takes care of closing connections in case of abnormal exits.
  328. Note that the effect of this specific example can be easier accomplished
  329. using the optional destructor argument of Win32::OLE::new:
  330. my $Excel = Win32::OLE->new('Excel.Application', sub {$_[0]->Quit;});
  331. Note that the delegation shown in the earlier example is not the same as
  332. true subclassing with respect to further inheritance of method calls in your
  333. specialized object. See L<perlobj>, L<perltoot> and L<perlbot> for details.
  334. True subclassing (available by setting C<@ISA>) is also feasible,
  335. as the following example demonstrates:
  336. #
  337. # Add error reporting to Win32::OLE
  338. #
  339. package Win32::OLE::Strict;
  340. use Carp;
  341. use Win32::OLE;
  342. use strict qw(vars);
  343. use vars qw($AUTOLOAD @ISA);
  344. @ISA = qw(Win32::OLE);
  345. sub AUTOLOAD {
  346. my $obj = shift;
  347. $AUTOLOAD =~ s/^.*:://;
  348. my $meth = $AUTOLOAD;
  349. $AUTOLOAD = "SUPER::" . $AUTOLOAD;
  350. my $retval = $obj->$AUTOLOAD(@_);
  351. unless (defined($retval) || $AUTOLOAD eq 'DESTROY') {
  352. my $err = Win32::OLE::LastError();
  353. croak(sprintf("$meth returned OLE error 0x%08x",$err))
  354. if $err;
  355. }
  356. return $retval;
  357. }
  358. 1;
  359. This package inherits the constructor C<new()> from the Win32::OLE
  360. package. It is important to note that you cannot later rebless a
  361. Win32::OLE object as some information about the package is cached by
  362. the object. Always invoke the C<new()> constructor through the right
  363. package!
  364. Here's how the above class will be used:
  365. use Win32::OLE::Strict;
  366. my $Excel = Win32::OLE::Strict->new('Excel.Application', 'Quit');
  367. my $Books = $Excel->Workbooks;
  368. $Books->UnknownMethod(42);
  369. In the sample above the call to C<UnknownMethod> will be caught with
  370. UnknownMethod returned OLE error 0x80020009 at test.pl line 5
  371. because the Workbooks object inherits the class C<Win32::OLE::Strict> from the
  372. C<$Excel> object.
  373. =head1 NOTES
  374. =head2 Hints for Microsoft Office automation
  375. =over 8
  376. =item Documentation
  377. The object model for the Office applications is defined in the Visual Basic
  378. reference guides for the various applications. These are typically not
  379. installed by default during the standard installation. They can be added
  380. later by rerunning the setup program with the custom install option.
  381. =item Class, Method and Property names
  382. The names have been changed between different versions of Office. For
  383. example C<Application> was a method in Office 95 and is a property in
  384. Office97. Therefore it will not show up in the list of property names
  385. C<keys %$object> when querying an Office 95 object.
  386. The class names are not always identical to the method/property names
  387. producing the object. E.g. the C<Workbook> method returns an object of
  388. type C<Workbook> in Office 95 and C<_Workbook> in Office 97.
  389. =item Moniker (GetObject support)
  390. Office applications seem to implement file monikers only. For example
  391. it seems to be impossible to retrieve a specific worksheet object through
  392. C<GetObject("File.XLS!Sheet")>. Furthermore, in Excel 95 the moniker starts
  393. a Worksheet object and in Excel 97 it returns a Workbook object. You can use
  394. either the Win32::OLE::QueryObjectType class method or the $object->{Version}
  395. property to write portable code.
  396. =item Enumeration of collection objects
  397. Enumerations seem to be incompletely implemented. Office 95 application don't
  398. seem to support neither the Reset() nor the Clone() methods. The Clone()
  399. method is still unimplemented in Office 97. A single walk through the
  400. collection similar to Visual Basics C<for each> construct does work however.
  401. =item Localization
  402. Starting with Office 97 Microsoft has changed the localized class, method and
  403. property names back into English. Note that string, date and currency
  404. arguments are still subject to locale specific interpretation. Perl uses the
  405. system default locale for all OLE transaction whereas Visual Basic uses a
  406. type library specific locale. A Visual Basic script would use "R1C1" in string
  407. arguments to specify relative references. A Perl script running on a German
  408. language Windows would have to use "Z1S1". Set the LCID module option
  409. to an English locale to write portable scripts. This variable should
  410. not be changed after creating the OLE objects; some methods seem to randomly
  411. fail if the locale is changed on the fly.
  412. =item SaveAs method in Word 97 doesn't work
  413. This is an known bug in Word 97. Search the MS knowledge base for Word /
  414. Foxpro incompatibility. That problem applies to the Perl OLE interface as
  415. well. A workaround is to use the WordBasic compatibility object. It doesn't
  416. support all the options of the native method though.
  417. $Word->WordBasic->FileSaveAs($file);
  418. The problem seems to be fixed by applying the Office 97 Service Release 1.
  419. =item Randomly failing method calls
  420. It seems like modifying objects that are not selected/activated is sometimes
  421. fragile. Most of these problems go away if the chart/sheet/document is
  422. selected or activated before being manipulated (just like an interactive
  423. user would automatically do it).
  424. =back
  425. =head2 Incompatibilities
  426. There are some incompatibilities with the version distributed by Activeware
  427. (as of build 306).
  428. =over 8
  429. =item 1
  430. The package name has changed from "OLE" to "Win32::OLE".
  431. =item 2
  432. All functions of the form "Win32::OLEFoo" are now "Win32::OLE::Foo",
  433. though the old names are temporarily accomodated. Win32::OLECreateObject()
  434. was changed to Win32::OLE::CreateObject(), and is now called
  435. Win32::OLE::new() bowing to established convention for naming constructors.
  436. The old names should be considered deprecated, and will be removed in the
  437. next version.
  438. =item 3
  439. Package "OLE::Variant" is now "Win32::OLE::Variant".
  440. =item 4
  441. The Variant function is new, and is exported by default. So are
  442. all the VT_XXX type constants.
  443. =item 5
  444. The support for collection objects has been moved into the package
  445. Win32::OLE::Enum. The C<keys %$object> method is now used to enumerate
  446. the properties of the object.
  447. =back
  448. =head2 Bugs and Limitations
  449. =over 8
  450. =item *
  451. To invoke a native OLE method with the same name as one of the
  452. Win32::OLE methods (C<Dispatch>, C<Invoke>, C<SetProperty>, C<DESTROY>,
  453. etc.), you have to use the C<Invoke> method:
  454. $Object->Invoke('Dispatch', @AdditionalArgs);
  455. The same is true for names exported by the Exporter or the Dynaloader
  456. modules, e.g.: C<export>, C<export_to_level>, C<import>,
  457. C<_push_tags>, C<export_tags>, C<export_ok_tags>, C<export_fail>,
  458. C<require_version>, C<dl_load_flags>,
  459. C<croak>, C<bootstrap>, C<dl_findfile>, C<dl_expandspec>,
  460. C<dl_find_symbol_anywhere>, C<dl_load_file>, C<dl_find_symbol>,
  461. C<dl_undef_symbols>, C<dl_install_xsub> and C<dl_error>.
  462. =back
  463. =head1 SEE ALSO
  464. The documentation for L<Win32::OLE::Const>, L<Win32::OLE::Enum>,
  465. L<Win32::OLE::NLS> and L<Win32::OLE::Variant> contains additional
  466. information about OLE support for Perl on Win32.
  467. =head1 AUTHORS
  468. Originally put together by the kind people at Hip and Activeware.
  469. Gurusamy Sarathy <[email protected]> subsequently fixed several major
  470. bugs, memory leaks, and reliability problems, along with some
  471. redesign of the code.
  472. Jan Dubois <[email protected]> pitched in with yet more massive redesign,
  473. added support for named parameters, and other significant enhancements.
  474. =head1 COPYRIGHT
  475. (c) 1995 Microsoft Corporation. All rights reserved.
  476. Developed by ActiveWare Internet Corp., now known as
  477. ActiveState Tool Corp., http://www.ActiveState.com
  478. Other modifications Copyright (c) 1997, 1998 by Gurusamy Sarathy
  479. <[email protected]> and Jan Dubois <[email protected]>
  480. You may distribute under the terms of either the GNU General Public
  481. License or the Artistic License, as specified in the README file.
  482. =head1 VERSION
  483. Version 0.1005 15 November 1998
  484. =cut