New or pre-loaded?

You may have noted that the LET statement in the above examples included the NEW keyword.  This tells PowerBASIC to request a new instance of the Object, rather than creating a reference to an existing instance.  This distinction can be important.  Let's imagine that you are creating a new instance of a component that produces its own GUI window.  Microsoft Word™ and many other EXE-based COM servers typically work this way.

Therefore, when using the NEW clause, a new instance of Microsoft Word is created regardless whether an instance of Word is already running.  That is, you could end up with two or more copies of Word running at the same time on the same PC.

In some situations this effect may be desirable, but there are also occasions where is it not.  In such situation, you should first try to create a reference to an existing instance, and if this fails, you can then try to create a new instance.  The general form of such code could look like this:

LET oWord = WordApplication IN "Word.Application"

IF ISFALSE ISOBJECT(oWord) THEN _

  LET oWord = NEW WordApplication IN "Word.Application"

Or you could even use structured error handling:

TRY

  LET oWord = WordApplication IN "Word.Application"

  IF ISFALSE ISOBJECT(oWord) THEN ERROR 5

CATCH

  LET oWord = NEW WordApplication IN "Word.Application"

  IF ISFALSE ISOBJECT(oWord) THEN _

    EXIT FUNCTION  ' MSWORD not installed or launchable?

END TRY

Finally, using the NEW keyword in order to create a new instance of the Object may add additional overhead - the Object might require a significant amount of time to start up, but this is obviously very dependent on the Object.  For example, the Windows Shell object is significantly faster to start than Microsoft Excel.

 

See Also

COM Programming Introduction

Under the hood

Methods and Properties