Click here to Skip to main content
Click here to Skip to main content

Adding Macro Scripting language support to existing MFC Application

, 18 Jul 2003 Apache
Rate this:
Please Sign up or sign in to vote.
Introduction to Microsoft Script Hosting and Adding Macro Scripting language support to existing MFC Application

Introduction

Writing applications that host a script engine to enable people to write scripts to customize and extend applications has proven to be very successful. There are thousands of developers using the Windows® Script engines in their applications and make no mistake about it, the Microsoft implementation is quite adequate if you want to add script (macro) capabilities to your application. The one good choice is to use the Active Scripting technology. First of all, Active Scripting technology uses existing scripting language, so you don't need to learn any new language. If you know how to program with VBScript, JavaScript or even PerlScript, that is all you need. In this article, I will present a simple alternative that allows you to add Scripting support to your application (even existing one).

Description

The Active Scripting architecture consists of a family of COM interfaces that defines a protocol for connecting a scripting engine to a host application. In the world of Active Scripting, a script engine is just a COM object that's capable of executing script code dynamically in response to either direct parsing or loading of script statements, explicit calls to the script engine's IDispatch interface, or outbound method calls (events) from the host application's objects. The host application can expose its automation interfaces to the script engine's namespace, allowing the application's objects to be accessed as programmatic variables from within dynamically executed scripts. A client application that needs to add script support only needs to implement Host portion of this technology. Different vendors may implement their own implementation of Engine, giving you now alternative to use other language that you already know. A good example is the PerlScript engine. A company may decide to use it instead of using JavaScript or VBScript in order to maintain existing code base.

Figure 1: Active Scripting architecture

Figure 2: Active Scripting COM Interaction

Figure 1 shows the basic architecture of Active Scripting, and Figure 2 shows sequence diagram detail of the COM interfaces defined by the architecture. Your client application that needs to use Active Scripting technology, creates and initializes a scripting engine based on the scripting language you want to parse, and you connect your application to the engine via the SetScriptSite method. You can then feed the engine script code that it can execute either immediately (not a function) or at some point in the future (function call), based on the script engine content and its state. For example, the following script text contains only global statements, and therefore could execute at parse time:

ScriptHost.Display("Hello CodeProject guru around the world.");

This statement would force the application to display a message box with the provide text (using the MFCScriptHost.exe Application) but:

function HostDisplay()
{
  ScriptHost.Display("Hello CodeProject guru around the world.");
}

would force the application to display this message only when HostDisplay() is called. But the good news is that this new method can also be accessed by your application whenever you want. To execute this function, your client application (Site object) needs to call GetIDsOfNames and Invoke of the IDispatch pointer of the script engine being used to force the execution of this function. Another cool feature of the Active Scripting technology is that you can add any automation object to the script engine items list and access its methods and properties from your script. In fact, these features are being used inside of Microsoft Office applications, Internet Explorer and Visual Studio. For example, you could have an item named 'Documents' and expose the list of opened documents in your application. Your implementation of the Script Site would call AddNamedItem("Documents") on the script engine interface pointer. For example, in our last example, the script engine gets a dispatch pointer of the "ScriptHost" named-item and call the "Display" method. But internally a lot of this process depends on the state of the Scripting Engine. That is the state of the engine must be started (SCRIPTSTATE_STARTED). At this point (when the engine is started), the engine would query the ActiveScriptSite object to resolve a named-item to a IDispatch interface pointer. It will then access that interface properties and methods by calling GetIDsOfNames and Invoke. This new item then becomes just like an internal variable that can be accessed whenever it needs it. Also, it becomes apparent how simple it is for the script engine to access the named-item properties and methods thanks to these two IDispatch interface methods.

But connecting event function to the script engine is a bit more tricky for many reasons. The more apparent reason is that the script engine must be able to do late-binding event support on a named-item. To support binding events to host named-item, Active Scripting engines use connection points to map outbound method calls/events from the host application's objects onto script functions. The way the named-item event function is called depends on the script language. VBScript uses a whole different approach to bind event call than JavaScript. Andrew Clinick's Scripting Events article give a lot more details than what I could cover here, so you may want to check it out.

I think this may be enough to get you start, now if you want to learn more, please check first the following References at the bottom of this article. This article was updated to show how the ScriptHost object can trigger event to the script.

Adding Scripting Support to your application

Now I have built this procedure that you can use to add scripting support to new or existing MFC application.

  1. The first step consists to creating an .ODL file (if your application doesn't have one). Advanced MFC developers could also fake this process by some others means (since we will not register this library) but I will not cover this here. You will have to generate a GUID by using GUIDGen.exe (available in tools folder of Visual Studio). A typical .ODL file would look like this
    // YourAppName.odl : type library source for YourAppName.exe
    
    // This file will be processed by the MIDL compiler to produce the
    // type library (YourAppName.tlb).
    
    [ uuid(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX), version(1.0) ]
    library YourAppName
    {
        importlib("stdole32.tlb");
        importlib("stdole2.tlb");
    
        //{{AFX_APPEND_ODL}}
        //}}AFX_APPEND_ODL}}
    };
    
  2. Use ClassWizard (Ctrl+W) to create an Automation object derived from CCmdTarget that will be the host object (ActiveScriptSite's client object). Define methods that you want to make available from your host. For example, you may have methods like: CreateActiveX(strProgID),DisplayMessage(strMessage), etc. Typically, these new dispatch methods would be called from a script.
  3. In your new class files, replace all references of CCmdTarget with CActiveScriptHost. At this point you will have to include ActiveScriptHost.h/cpp to your project.
  4. *UPDATED* Override the virtual function HRESULT GetClassID( LPCLSID pclsid ). It must return successfully the CLSID of your host object. The CSLID can be found in the .ODL file once you create the automation object in step 2. Typical implementation will look like this:
    HRESULT CHost_Proxy::GetClassID( LPCLSID pclsid )
    {
        *pclsid = CLSID_Host_Proxy;
        return S_OK;
    }
    Note also that at this point our object is really a COM object and ActiveX control but we will not register as we would normally do.
  5. *UPDATED* You will need to declare the type library that you are using. This step is tricky but using MFC macro, it is a lot easier. Just add DECLARE_OLETYPELIB(CYourHost_Proxy) in the header file of your proxy class and IMPLEMENT_OLETYPELIB(CYourHost_Proxy, _tlid, _wVerMajor, _wVerMinor) in the .cpp file. _tlid is the GUID of the typelibrary (step 1) and _wVerMajor/_wVerMinor represent the version number of your typelibary. Also, use the resource include editor to add these directives.
    #ifdef _DEBUG
    1 TYPELIB "Debug\\YourAppName.tlb"
    #else
    1 TYPELIB "Release\\YourAppName.tlb"
    #endif
  6. *NEW* Now Add an event-source object, for example:
    [ uuid(740C1C2D-692F-43F8-85FF-38DEE1742819) ]
    dispinterface IHostEvent
    {
        properties:
        methods:
        [id(1)] void OnRun();
        [id(2)] void OnAppExit();
    };
    //  Class information for CHost_Proxy
    [ uuid(F8235A29-C576-439D-A070-6E7980C9C3F6) ]
    coclass Host_Proxy
    {
        [default] dispinterface IHost_Proxy;
        [default, source] dispinterface IHostEvent;
    };
    
    As you can see in this example, our Host now supports two events that we can trigger directly from our code by using COleControl::FireEvent function. Such functions are very simple. For example:
    void FireOnRun()
        {FireEvent(eventidOnRun,EVENT_PARAM(VTS_NONE));}
    void FireOnAppExit()
        {FireEvent(eventidOnAppExit,EVENT_PARAM(VTS_NONE));}
    
  7. Create an instance of your host object (can also be a dynamically-created class by using MFC macro) and call CYourHostProxy::CreateEngine( 'Language ProgID' ) which can be 'JavaScript' or 'VBScript' if you want to use these engine.
  8. Add implementation code to your proxy methods to do what you wish to let the advanced users do with your application.
  9. Add any additional named-item object that you wish to access from script language
  10. Provide way for the user to create script or load script text from disk. CActiveScriptHost class provide helper functions that you may want to reuse based on functionalities that you want to give in your application. By the way, it is not safe to let user create Inproc-ActiveX object but Local-server is generally good. One good reason not to let the user create ActiveX control is that, if a crash occurred inside of the ActiveX, your application should not. Local-server give you freely this kind of safety.

Revision History

////////////////////////////////////////////////////////
//  Version history
// v1.01 : Bug fix with accessing object info (ITypeInfo)
// v1.10 : Add 'InvokeFuncHelper' allows to call script 
//         function directly from c++
// v1.5  : Add support for Host event (now derive from COleControl 
//         instead of CCmdTarget)
////////////////////////////////////////////////////////

References

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0

Share

About the Author

Ernest Laurentin
Software Developer (Senior)
United States United States
Ernest is a multi-discipline software engineer.
Skilled at software design and development for all Windows platforms.
-
MCSD (C#, .NET)
Interests: User Interface, GDI/GDI+, Scripting, Android, iOS, Windows Mobile.
Programming Skills: C/C++, C#, Java (Android), VB and ASP.NET.
 
I hope you will enjoy my contributions.

Comments and Discussions

 
QuestionHow to use 'Sleep()' , in 'Do While ~ Loop' Pinmemberklrodel11-Dec-14 15:06 
QuestionMultithread support PinmemberFINAL BOSS22-Apr-13 1:58 
QuestionHow to pass the array into event? PinmemberFINAL BOSS9-Apr-13 19:48 
AnswerRe: How to pass the array into event? PinmemberErnest Laurentin9-Apr-13 21:01 
GeneralRe: How to pass the array into event? PinmemberFINAL BOSS9-Apr-13 21:44 
GeneralRe: How to pass the array into event? PinmemberErnest Laurentin9-Apr-13 22:16 
GeneralRe: How to pass the array into event? PinmemberFINAL BOSS9-Apr-13 22:51 
QuestionI really want to know how can I pass the JS ARRAY to the MFC function PinmemberChongxi22-Feb-12 23:30 
GeneralDynamic creat a Button,vbs not surppor?t [modified] PinmemberEvanescence Lee5-Sep-08 18:26 
AnswerRe: Dynamic creat a Button,vbs not surppor?t PinmemberErnest Laurentin15-Sep-08 12:22 
In ActiveScriptHost.cpp (CActiveScriptHost::AddScriptCode)
Uncomment these lines:
hr = m_pAxsScript->SetScriptState(SCRIPTSTATE_CONNECTED);
HRESULT_EXCEPTION::CheckError( hr ); // will throw an exception if failed
As for your script, I've used btnGo_Click instead. I noticed you are creating the second button manually, you may need to serialize some other properties as well.
 

In the end, we will remember not the words of our enemies, but the silence of our friends. - Martin Luther King Jr.
Ernest Laurentin

GeneralRe: Dynamic creat a Button,vbs not surppor?t PinmemberEvanescence Lee15-Sep-08 19:03 
GeneralRe: Dynamic creat a Button,vbs not surppor?t PinmemberErnest Laurentin17-Sep-08 7:15 
GeneralRe: Dynamic creat a Button,vbs not surppor?t PinmemberEvanescence Lee17-Sep-08 21:30 
GeneralRe: Dynamic creat a Button,vbs not surppor?t [modified] PinmemberEvanescence Lee18-Sep-08 22:39 
GeneralRe: Dynamic creat a Button,vbs not surppor?t PinmemberEvanescence Lee21-Sep-08 3:33 
GeneralRe: Dynamic creat a Button,vbs not surppor?t PinmemberErnest Laurentin21-Sep-08 7:54 
GeneralRe: Dynamic creat a Button,vbs not surppor?t [modified] PinmemberEvanescence Lee21-Sep-08 17:36 
Generaluse vbs , and some of event can't touch off . Pinmemberpretty_kiddy18-May-08 19:46 
AnswerRe: use vbs , and some of event can't touch off . PinmemberErnest Laurentin20-May-08 5:59 
QuestionHow get return value or modified argument from event ? Pinmemberachainard18-Jun-07 2:31 
AnswerRe: How get return value or modified argument from event ? PinmemberErnest Laurentin26-Jun-07 11:21 
GeneralRe: How get return value or modified argument from event ? Pinmemberachainard26-Jun-07 18:16 
QuestionLimit creation of ActiveX Objects?? Pinmembertunafish242-Feb-07 16:56 
AnswerRe: Limit creation of ActiveX Objects?? PinmemberErnest Laurentin3-Feb-07 9:32 
QuestionExceptions from own script object Pinmemberschultz.tom1-Nov-06 8:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141216.1 | Last Updated 19 Jul 2003
Article Copyright 2002 by Ernest Laurentin
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid