AutoCmd (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

The following code shows how to use the Exec method to invoke the methods of an Automation interface that is assigned to a Variant object. It first declares AutoCmd descendants that represent methods on the interface that is assigned to the Variant. The parameters to these methods are initialized when the form is created. To your form, add a memo component named memTextForWord and four buttons named btnStartWord, btnStopWord, btnNewDoc, and btnInsertText, respectively. Assign the OnClick event handlers in the example, which use the Exec method to execute the AutoCmd descendants.

Note: It may be necessary to use localized names for the property names. For instance, when using a German version of Word, use "Beenden" instead of "Quit" and "Sichtbar" instead of "Visible". Contact the supplier of your Automation server to determine whether its commands are locale sensitive.

Code

/* Declare global Variant for Automation interface */
Variant MSWord;

/* Declare AutoCmd objects for methods on Automation interface */
PropertySet VisTrue("Visible");
Procedure QuitFalse("Quit");
PropertyGet GetDocs("Documents");
PropertyGet GetSel("Selection");
Function DocAdd("Add");
Procedure AddText("TypeText");
Procedure AddDate("InsertDateTime");
Procedure AddPara("TypeParagraph");

__fastcall TfrmWordCtrl::TfrmWordCtrl(TComponent* Owner)
	: TForm(Owner)
{
	/* Initialize AutoCmd objects with their parameters */
	VisTrue << true;
	QuitFalse << false;

	/* Set up named parameters for date/time method call */
	AddDate <<
		NamedParm("DateTimeFormat", "dddd, dd MMMM yyyy") <<
		NamedParm("InsertAsField", false);
}

void __fastcall TfrmWordCtrl::btnStartWordClick(TObject *Sender)
{
	MSWord = Variant::CreateObject("Word.Application");
	MSWord.Exec(VisTrue);
}

void __fastcall TfrmWordCtrl::btnStopWordClick(TObject *Sender)
{
	/* Should be able to just use the 2nd statement but MS Office 97 doesn't
	adhere to the lifetime management aspects of the MS COM spec. */

	MSWord.Exec(QuitFalse);
	MSWord = Unassigned;
}

void __fastcall TfrmWordCtrl::btnNewDocClick(TObject *Sender)
{
	/* Invoke the new document APIs from Word */
	Variant DocCollection = MSWord.Exec(GetDocs);
	DocCollection.Exec(DocAdd);
}

void __fastcall TfrmWordCtrl::btnInsertTextClick(TObject *Sender)
{
	/* Set document text */
	Variant Sel = MSWord.Exec(GetSel);
	AddText.ClearArgs();

	Sel.Exec(AddText << WideString(memTextForWord->Text));
	Sel.Exec(AddDate);
	Sel.Exec(AddPara);
}

Uses