Have an amazing solution built in RAD Studio? Let us know. Looking for discounts? Visit our Special Offers page!
DelphiTech Partner

How To Automate The Mathcad Prime Software With Delphi Using COM

How To Automate The Mathcad Prime Software With Delphi
How To Automate The Mathcad Prime Software With Delphi   the Softacom logo

Among the most notable features of Delphi, itโ€™s worth mentioning the ability to enhance your Windows app development by interacting with other installed software products on your computer, using the COM technology for functionality embedding or automating.

In this article, we will show you how to automate the Mathcad Prime software in your Delphi VCL apps, by controlling the automation server and the fundamental methods and properties of its API, and how to implement an event sink in your app to handle events triggered by the Mathcad Prime software.

Mathcad Prime is an engineering calculation software developed by PTC. It is used by engineers to solve, document, and share calculations for product design.

It provides an Automation API as a type library (TLB), that you can import in Delphi IDE and use in your apps to launch the software, send data to be treated and analyzed in the opened worksheet, and get the result back to be shown in your app.

This can be done using Microsoftโ€™s COM technology, which is a language-independent software component model that enables interaction between software components (the COM server) and developed applications (the COM client) running on the  Windows platform. The COM client can be either on the same computer as the server or on another computer on the network (connected through the Distributed COM (DCOM) mechanism).

How To Automate The Mathcad Prime Software With Delphi Using COM   an image of a math book's page

The key aspect of COM is that it enables the communication between clients and servers through interfaces clearly defined by the server developer. These interfaces provide a way for clients to ask a COM component which features it supports at run time. And to develop a COM client, you must understand the interface (properties and methods) exposed by the server to clients.

In order to access this interface, its type information is typically published as a type library that can be imported and used in Delphi VCL projects.

To get specific information about the published interfaces of PTC Mathcad Prime, check the developer documentation here.

Importing Mathcad Prime API to Delphi

For communication with Mathcad Prime, you have to access its API through the โ€œPtc.MathcadPrime.Automation.dllโ€ installed at the software top level of the installation directory.

  • Open or create a new Delphi VCL project, and go to the menu โ€œComponents>Import a componentโ€.
  • In the new dialog window, choose โ€œImport a type libraryโ€ and click โ€œNextโ€.
  • Click โ€œAddโ€ and browse to the file โ€œPtc.MathcadPrime.Automation.tlbโ€.
  • Create a unit for this type library (there is no need to install it on the Components Palette), or add it to the current project.

Now, Delphi will generate the unit โ€œPtc_MathcadPrime_Automation_TLBโ€ that will be specific to the installed version of Mathcad Prime. You can save it for later use.

COM Client implementation

To implement your COM Client app, start a new (or open an existing) VCL project.

In the uses clauses, add your generated TLB unit and the following unit:

As you can see in the generated unit, the Mathcad Prime automation server has a dual interface, which will make the implementation tasks much easier (You can find the basics of using COM interfaces in Delphi documentation).

We need the following global variables to be used in the project:

Variable forPurposes and possible tasksVariable type and its constructor and destructor
Mathcad Prime main applicationStarting, hiding and closing the application.

 

Creating a new (or opening an existing) worksheet.

Closing the active worksheet.

IMathcadPrimeApplication3

 

Constructor : โ€œCoApplication.Createโ€

Destructor : assign a nil value

Mathcad Prime active worksheetSaving the worksheet.

 

Exchanging data between the server and client.

IMathcadPrimeWorksheet3

 

Constructor : โ€œIMathcadPrimeApplication3.Open() as IMathcadPrimeWorksheet3โ€

Destructor : โ€œIMathcadPrimeApplication3.Close()โ€

Mathcad Prime eventsHandling events raised by the userโ€™s actions on the server app.IMathcadPrimeEvents2

 

Constructor : (TMathcadPrimeEvents.Create)

Destructor : assign a nil value

So, we will declare variables as follows:

These variables are used in the code snippets as mentioned above.

Basic tasks

Now we will illustrate how you can use the Mathcad Prime API through some basic tasks. And :

  • Use the โ€œtry โ€ฆ except โ€ฆ end;โ€ instruction to force the code execution and to handle exceptions.
  • In case of exception’s detection, show a message to inform the user about the taskโ€™s failure.

Start the application

For starting the app, implement the โ€œtry โ€ฆ except โ€ฆ end;โ€ instruction to create an instance of the โ€œIMathcadPrimeApplication3โ€ interface (through the constructor of the โ€œCoApplicationโ€ class) and assign it to the Application variable, and set the Application โ€œVisibilityโ€ property to โ€œTrueโ€.

Or, in the case of an exception, show a failure message with the exception message.

Close the application

For closing the app, implement a condition to check if the Application variable is assigned (the variable does not have a null value), then release it by calling the Application โ€œQuit()โ€ method with the parameter โ€œSaveOption_spSaveChangesโ€. Or show a failure message if an exception is detected.

Show the application

To activate the app and bring it to the front, implement a condition to check if the Application variable is assigned, then set the Application โ€œVisibilityโ€ property to โ€œTrueโ€ and call the โ€œActivate()โ€ method. Or show a failure message for the exception.

Hide the application

To hide the app, implement a condition to check if the Application variable is assigned, then set the Application โ€œVisibilityโ€ property to โ€œFalseโ€. Or show a failure message in the case of an exception.

Get the active worksheet in the application

To get an active worksheet in the app (to exchange data between the worksheet and the client app), implement a condition to check if the Application variable is assigned, then assign the Application โ€œActiveWorksheetโ€ property value to the Worksheet variable.

(Use type casting, because the Application โ€œActiveWorksheetโ€ type is not โ€œIMathcadPrimeWorksheet3โ€).

Open an existing worksheet in the application

  • First of all, you need a โ€œTOpenDialogโ€ with the filter โ€œMCDX files (*.mcdx)โ€ for Mathcad Prime worksheets, you have to set it either on design-time or on run-time through codes like in the snippet below.
  • Next, implement a condition to check if the Application variable is assigned, then โ€œExitโ€ the procedure.
  • Now, if the Application variable is assigned, the procedure will continue and the โ€œTOpenDialogโ€ is executed.
  • To open the selected file, implement the โ€œtry โ€ฆ finally โ€ฆ end;โ€ instruction to call the Application โ€œOpenโ€ function with the selected fileโ€™s name as a parameter, and assign the resulting value to the Worksheet variable (Use type casting). Or show a failure message in the case of an exception.

Create a new worksheet in the application

To create a new worksheet in the app, implement a condition to check if the Application variable is assigned, then call the Application โ€œOpenโ€ function with an empty string as a parameter and assign the resulting value to the Worksheet variable (Use type casting).

Save modifications in the opened worksheet in the application

To save modifications in the active worksheet (existing as a local file) in the app, implement a condition to check if both Application and Worksheet variables are assigned, then call the Worksheet โ€œSaveโ€ method. Or show a failure message in the case of an exception.

Save the worksheet in the application as Mathcad worksheet (MCDX)

  • First of all, you need a โ€œTSaveDialogโ€ option with the filter โ€œMCDX files (*.mcdx)โ€ for Mathcad Prime worksheets, you have to set it either on design-time or on run-time through codes like in the snippet below.
  • Next, implement a condition to check if the Application variable is assigned, then โ€œExitโ€ the procedure.
  • Also, implement a condition to check if the Worksheet variable (the active worksheet) is assigned, then show a message to get the active worksheet, and โ€œExitโ€ the procedure.
  • Now, if both Application and Worksheet variables are assigned, the procedure will continue and the โ€œTSaveDialogโ€ is executed.
  • To save as the selected file, implement the โ€œtry โ€ฆ finally โ€ฆ end;โ€ instruction to call the Worksheet โ€œSaveAsโ€ function with the designated filename as a parameter. Or show a failure message in the case of an exception.

Save the worksheet in the application as a Mathcad template (MCTX)

It will be the same code as the previous one, but you have to change the filter and the default extension to โ€œMCTXโ€.

Close the active worksheet in the application

To close the active worksheet in the app, implement a condition to check if both Application and Worksheet variables are assigned, then:

  • Call the Worksheet โ€œCloseโ€ method with the parameter โ€œSaveOption_spDiscardChangesโ€. Or show a failure message in the case of exception.

Now, to destroy the Worksheet object, add a condition to check if the Worksheet variable is assigned, then set its value to null.

The event sink

Your client app can also respond to the events raised by the COM server. And to do this, you can simply use the events added to the generated component in the Object inspector. But if you are not using a Component wrapper or if the server uses COM+ events, you have to implement an event sink.

As it may sound difficult, in this section, we will show you how to properly implement an event sink for the Mathcad Prime COM server.

Interface descending class

Mathcad Prime events are declared in the interface โ€œIMathcadPrimeEvents2 โ€œ, you can find it in the โ€œPtc_MathcadPrime_Automation_TLBโ€ unit:

Now, either on a new separate unit or in your existing projectโ€™s unit, declare the class โ€œTMathcadPrimeEventsโ€ with descendance from both โ€œTInterfacedObjectโ€ and โ€œIMathcadPrimeEvents2โ€, like the following:

Now, the followimg positions should be added to this class :

  • A boolean variable called โ€œShowEventsโ€.
  • A constructor method (To initialize the ShowEvents value as โ€œFalseโ€).
  • The โ€œTMathcadPrimeEventsโ€ interface methods (copy them from the โ€œPtc_MathcadPrime_Automation_TLBโ€ unit).

Methods implementation

Implement the event’s class methods as the following way:

  • In the constructor, set the ShowEvents variable value to โ€œFalseโ€.
  • In โ€œIMathcadPrimeEvents2โ€ methods, implement a condition to check if ShowEvents variable is โ€œTrueโ€ then show a message to provide information about the nature of the event triggered by the COM server. You need to implement only these โ€œIMathcadPrimeEvents2โ€ events :
    • OnExit
    • OnWorksheetClosed
    • OnWorksheetModified
    • OnWorksheetRenamed
    • OnWorksheetSaved

All these functions have to return the โ€œS_OKโ€ value when their executions have successed. They are used by the COM server to get interfaces and call the appropriate eventโ€™s handler.

For the โ€œIUnknownโ€ interface methods โ€œQueryInterfaceโ€, โ€œ_AddRefโ€ and โ€œ_Releaseโ€, their implementations are inherited from the ascending class โ€œTInterfacedObjectโ€, so there is no need to re-implement them.

For now, your โ€œTMathcadPrimeEventsโ€ class implementation will look like the code below:

Save the event sink unit to be used later.

Connecting the event sink

  • Add the event sink unit to the uses clauses of your COM clientโ€™s main unit.
  • Declare an integer variable such as โ€œFConnectionTokenโ€.
  • In the FormCreate event handler, create an instance of the class โ€œTMathcadPrimeEventsโ€ and assign it to the global โ€œEventsโ€ variable.

Go to the method for starting Mathcad Prime app, and :

  • Declare an integer variable such as โ€œisMathcadPrimeEvents2Initialized โ€œ.
  • After the Application instance creation code, call the method โ€œInterfaceConnectโ€ with the parameters :
    • The Application variable
    • โ€œIMathcadPrimeApplication3โ€ interface
    • The Events variable
    • The โ€œFConnectionTokenโ€ variable
  • Implement a condition to check if the Application variable is assigned, then :
    • Call the Application โ€œInitializeEvents2โ€ function with the parameters (the Events variable and โ€œTrue”), and assign the resulting value to the variable โ€œisMathcadPrimeEvents2Initializedโ€.
    • Implement a condition to check if the Events variable has a null value or if the โ€œisMathcadPrimeEvents2Initializedโ€ have a value other than zero, then show a failure message โ€œEvents initialization failedโ€.
  • Else, raise an exception with the message โ€œProblem to connect Mathcad Primeโ€.

In the FormClose event handler, by using the โ€œtry โ€ฆ except โ€ฆ endโ€ instruction :

  • Call the method โ€œInterfaceDisconnectโ€ with the parameters (The Application variable, โ€œIMathcadPrimeApplication3โ€ interface, and the โ€œFConnectionTokenโ€ variable).
  • Assign a null value to both Application and Events variables.
  • In the case of an exception, just close the form.

Enable/Disable the events

It would be nice if we implemented something like radio buttons to enable/disable the events handling.

Drop a TRadioGroup control, with two items (Enable, and Disable). Then open its “OnClick” event and implement a switch case condition:

  • If a selected item is โ€œEnabledโ€: Write a condition to check the Events variable if it is assigned and it belongs to the โ€œTMathcadPrimeEventsโ€ class, then cast the Events variable to the โ€œTMathcadPrimeEventsโ€ class and set the โ€œShowEventsโ€ fieldโ€™s value to โ€œTrueโ€. Or, show a message on failure.
  • If a selected item is โ€œDisabledโ€: Then set the โ€œShowEventsโ€ fieldโ€™s value to โ€œFalseโ€.

Run the project

The automation works in Delphi without the need to deploy the โ€œPtc.MathcadPrime.Automation.dllโ€ library. So just run your project.

How To Automate The Mathcad Prime Software With Delphi Using COM   COM client app

Check the features of your COM Client app:

  • Click โ€œStart Mathcad Primeโ€ and wait until Mathcad Prime opens.
  • Click โ€œShow Mathcad Primeโ€ to bring Mathcad Prime to the foreground.
  • Click โ€œHide Mathcad Primeโ€ to hide Mathcad Prime.
  • Click โ€œOpen Worksheetโ€ to browse to the worksheet that you want to open, then make sure that the worksheet is opened.
  • Click โ€œOpen New Worksheetโ€ and make sure that a new worksheet entitled Untitled-n is opened.
  • Click โ€œClose Worksheetโ€ and make sure that the last opened worksheet is closed.
  • To check the events:
    • Click โ€œEnable Eventsโ€.
    • Click the worksheet and type something, a message appears indicating that a modified event has occurred, click โ€œOKโ€ to dismiss the message.
    • Click โ€œSave Asโ€, and a message appears indicating that a renamed event has occurred, click โ€œOKโ€ to dismiss the message.
    • Click โ€œClose Worksheetโ€, and a message appears indicating that a close event has occurred, click โ€œOKโ€ to dismiss the message.
  • Click โ€œClose Mathcad Primeโ€ to close Mathcad Prime, and close the project.

This article was written by Embarcadero Tech Partner Softacom. Softacom specialize in all sorts of software development focused on Delphi. Read more about their services on the Softacom website.

What What's New in InterBase 15 See What's New in RAD Studio 13 Florence The AI Codecamp: Learn, Code, Create

Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder.
Design. Code. Compile. Deploy.
Start Free Trialย ย ย Upgrade Today

ย ย ย Free Delphi Community Editionย ย ย Free C++Builder Community Edition

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

IN THE ARTICLES