TABLE OF CONTENTS

ws4ahk

About

Windows Scripting for Autohotkey (stdlib) v0.21 beta

Requires Autohotkey v1.0.47 or above.

Home page: http://www.autohotkey.net/~easycom/

This module contains functions to embed VBScript or JScript into your AHK program, and as such, provides simple access to COM though these languages. This module also provides functions to create COM controls which can be controlled via VBScript or JScript.

You might also look at this module as a means to add GUI abilities to VBScript/JScript. These Microsoft Scripting languages do not natively provide a way to show Windows, or even call DLL functions. By combining these Microsoft Scripting languages with Autohotkey, you get the best of both worlds.

Note that this module requires use of the "Microsoft Scripting Control" which is usually installed on most machines. In the rare case it is not installed on a system, it may be downloaded from Microsoft and installed.

http://www.microsoft.com/downloads/details.aspx?FamilyId=D7E31492-2595-49E6-8C02-1426FEC693AC

As an alternative, the Microsoft Scripting Control file "msscript.ocx" may be used directly (e.g. placed in the same folder as the AHK script), so there is no need to actually install it (see WS_Initialize for how).

Links

List of Automation errors http://support.microsoft.com/kb/186063

VBScript Language Reference http://msdn2.microsoft.com/en-us/library/d1wf56tt.aspx

JScript Language Reference http://msdn2.microsoft.com/en-us/library/yek4tbz0.aspx

The MSDN guru on WSH http://blogs.msdn.com/ericlippert/archive/2004/07/14/183241.aspx

MSDN article "Adding Scripting Support to Your Application" goes over the functions of the Microsoft Scripting Control. http://msdn.microsoft.com/en-us/library/aa227413(VS.60).aspx

To Do

License

Copyright (c) 2007,2008 erictheturtle of AutoHotKey forums

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

WS_Initialize

Description

Initializes the Windows Scripting environment.

Usage

WS_Initialize( [ sLanguage = "VBScript" [, sMSScriptOCX ] ] )

Parameters

Return Value

(Boolean) True on success, False on failure.

ErrorLevel

Remarks

This function must be called before any other functions may be used.

Normally the scripting environment is setup using the installed msscript.ocx file on the system. Alternatively, you may specify the path directly to a msscript.ocx file, even if it is not registered with the system (useful if the user does not have Microsoft Scripting Control installed).

Repeated calls to this function are ignored.

Related

WS_Uninitialize

Example

    WS_Initialize()
    ; do stuff
    WS_Uninitialize()
    
    WS_Initialize("VBScript", "C:\Windows\system32\msscript.ocx")
    ; do stuff
    WS_Uninitialize()

WS_Uninitialize

Description

Uninitializes the Windows Scripting environment and releases the allocated resources.

Usage

WS_Uninitialize()

Return Value

None ("").

ErrorLevel

If an error occured while trying to release allocated resources, ErrorLevel will be set to an error description. If no error occured, ErrorLevel is unchanged.

Remarks

Call this function to free the memory used by this library. It is not necessary to call this function before exiting your script (but it is good practice).

This function may be called repeatedly.

Related

WS_Initialize

Example

    ; see WS_Initialize example

WS_Exec

Description

Executes scripting code.

Usage

WS_Exec(sScriptCode)

Parameters

Return Value

(Boolean) True on success, False on failure.

ErrorLevel

Remarks

If WS_Initialize() has not been called, an error message will be displayed and the program will exit.

By default, the Microsoft Scripting Control only allows scripts to run for 5 seconds before considering it 'hung', and the script is stopped (this can be changed, but hasn't been implemented in this library).

Related

WS_Eval, VBStr, JStr

Example

    #Include ws4ahk.ahk
    WS_Initialize()
    ; Using a block of code like this makes it easy to
    ; add functions to the scripting environment.
    ; But always be sure to escape any percent signs (%)
    Code = 
    (
        foo = "bar"
        Sub MsgFoo()
            Msgbox foo
        End Sub
    )
    WS_Exec(Code)
    WS_Exec("MsgFoo")

WS_Eval

Description

Evaluates scripting code and returns the result.

Usage

WS_Eval(ByRef ReturnValue, sScriptCode)

Parameters

Return Value

(Boolean) True on success, False on failure.

ErrorLevel

Remarks

ReturnValue will hold the result of an evaluation. Most return types are handled. Unhandled types are: Array, Currency, Date, VARIANT*, and the mysterious DECIMAL* type. You must convert these unhandled types to another type (usually string) before they can be returned.

If an expression results in an unhandled type, the function will return True (because the expression was evaluated), but ReturnValue will be set to "#Unhandled return type#".

Note also that if the expression returns an object, the object should be released via the WS_ReleaseObject() function when it is no longer needed.

If WS_Initialize() has not been called, an error message will be displayed and the program will exit.

By default, the Microsoft Scripting Control only allows scripts to run for 5 seconds before considering it 'hung', and the script is stopped (this can be changed, but hasn't been implemented in this library).

Related

WS_Exec, VBStr, JStr

Example

    #Include ws4ahk.ahk
    WS_Initialize()
    Code = 
    (
        Function Square(x)
            Square = x * x
        End Function
    )
    WS_Exec(Code)
    WS_Eval(Ret, "Square(6)")
    Msgbox % Ret

VBStr

Description

Wraps a string in quotes and escapes disallowed characters for use in VBScript.

Usage

VBStr(str)

Parameters

Return Value

(String) Escaped string.

ErrorLevel

Not changed.

Remarks

Converts an Autohotkey string into a string usable in the scripting environment. Specifically, it escapes disallowed characters (e.g. quotes, carriage return) and, wraps the string in quotes.

Related

JStr, WS_Exec, WS_Eval

Example

    #Include ws4ahk.ahk
    text := VBStr("this is ""a test""")
    Msgbox % text
    ; This is equivalent to
    ; text := """this is """"a test"""""""
    

    text = 
    (
    Multi
    Line
    Text
    )
    text := VBStr(text)
    Msgbox % text
    ; This is equivalent to
    ; text := """Multi"" & vbLf & ""Line"" & vbLf & ""Text"""   

JStr

Description

Wraps a string in quotes and escapes disallowed characters for use in JScript.

Usage

JStr(str)

Parameters

Return Value

(String) Escaped string.

ErrorLevel

Not changed.

Remarks

Converts an Autohotkey string into a string usable in the scripting environment. Specifically, it escapes disallowed characters (e.g. quotes, carriage return) and, wraps the string in quotes.

Related

VBStr, WS_Exec, WS_Eval

Example

    #Include ws4ahk.ahk
    text := JStr("this is ""a test""")
    Msgbox % text
    ; This is equivalent to
    ; text := """this is \""a test\"""""
    

    text = 
    (
    Multi
    Line
    Text
    )
    text := JStr(text)
    Msgbox % text
    ; This is equivalent to
    ; text := "\""Multi\nLine\nText\""" 

WS_CreateObject

Description

Creates a new instance of a COM object.

Usage

WS_CreateObject(sProgIDorClassID [, sInterfaceID = IDispatch ] )

Parameters

Return Value

ErrorLevel

Remarks

In most cases it is better and faster to use the scripting environment to create and manage objects (using VBScript's CreateObject() function, and JScript's ActiveXObject() function).

WS_ReleaseObject() should be called when the object is no longer needed.

Note that the sInterfaceID parameter is only used for more advanced COM operations. Normally it can be ignored.

Related

WS_ReleaseObject

Example

    ; This is a contrived example. Normally it is better and faster to use
    ; VBScript's CreateObject() function (or JScript's ActiveXObject() function).
    #Include ws4ahk.ahk
    WS_Initialize()
    pSpObj := WS_CreateObject("SAPI.SpVoice")
    WS_AddObject(pSpObj, "oSpeak")
    WS_ReleaseObject(pSpObj) ; scripting environment has object, we don't need it anymore
    WS_Exec("oSpeak.Speak %s", "Hello world!")

WS_GetObject

Description

Get the instance of an already existing COM object.

Usage

WS_GetObject(sProgIDorClassID [, sInterfaceID = IDispatch ] )

Parameters

Return Value

ErrorLevel

Remarks

In most cases it is better and faster to use the GetObject() function in the scripting environment instead of this function.

WS_ReleaseObject() should be called when the object is no longer needed.

Note that the sInterfaceID parameter is only used for really advanced COM operations. Normally it can be ignored.

Related

WS_ReleaseObject

Example

    ; This example works best if Microsoft Excel is installed.
    ; This is a contrived example. Normally it is better and faster to use
    ; the script's GetObject() function. 
    #Include ws4ahk.ahk
    WS_Initialize()
    pExcel := WS_GetObject("Excel.Application")
    
    If (pExcel = "")
    {
        Msgbox % "Excel isn't running."
    }
    Else
    {
        WS_AddObject(pExcel, "oExcel")
        WS_ReleaseObject(pExcel)
        WS_Eval(iWrkBks, "oExcel.Workbooks.Count")
        Msgbox % "You have " iWrkBks " workbook(s) open in Excel."
    }

WS_ReleaseObject

Description

Frees a reference to an object.

Usage

WS_ReleaseObject(pObject)

Parameters

Return Value

ErrorLevel

Remarks

Should be called on object pointers that are no longer needed so the reference can be freed.

Calling this function on an object that is already released will crash your program!

Related

WS_CreateObject

Example

    #Include ws4ahk.ahk
    WS_Initialize()
    ; Create an object in the scripting environment and return it to AHK
    WS_Eval(oObj, "CreateObject(%s)", "Wscript.Shell")
    ; ... do something with the object
    WS_ReleaseObject(oObj)

WS_AddObject

Description

Adds a COM object to the scripting environment.

Usage

WS_AddObject(pObject, sName [, blnGlobalMembers = False ] )

Parameters

Return Value

(Boolean) True on success, False on failure.

ErrorLevel

Remarks

Adds an object created in AHK to the scripting environment. Setting blnGlobalMembers to True will make all the members of the object global in the script.

This function is most useful after creating a COM control. The COM object can be added to the scripting environment, and then the object can be controlled via the script.

If WS_Initialize() has not been called, an error message will be displayed and the program will exit.

Related

WS_ReleaseObject

Example

    ; see WS_CreateObject example

WS_InitComControls

Description

Initializes COM controls.

Usage

WS_InitComControls()

Return Value

ErrorLevel

Set to DllCall() result.

Remarks

Must be called before calling WS_CreateComControlContainer.

WS_Initialize() does not need to be called before calling this function.

There is no harm in calling this function more than once.

Related

WS_UninitComControls, WS_CreateComControlContainer

Example

    ; see WS_CreateComControlContainer example

WS_UninitComControls

Description

Uninitializes COM controls.

Usage

WS_UninitComControls()

Return Value

None ("").

ErrorLevel

Set to DllCall() result.

Remarks

Unloads the atl library.

WS_Initialize() or WS_Uninitialize() do not need to be called before calling this function.

Note: MSDN warns about a race condition that could occur if two threads called this function at the same time.

http://msdn2.microsoft.com/en-us/library/ms885630.aspx

Related

WS_InitComControls

Example

    ; see WS_CreateComControlContainer example

WS_GetHWNDofComControl

Description

Retrieves the Window Handle (i.e. hWnd, or ahk_id) associated with a COM control object.

Usage

WS_GetHWNDofComControl(pObject)

Parameters

Return Value

ErrorLevel

Remarks

WS_CreateComControlContainer will return the hWnd when it creates the COM control. As such, this function isn't really necessary unless the COM control is created some other way, or the hWnd is somehow unavailable in a scope.

WS_Initialize() does not need to be called before calling this function.

Related

WS_GetComControlInHWND, WS_AttachComControlToHWND

Example

WS_GetComControlInHWND

Description

Retrieves the COM control object associated with a COM control.

Usage

WS_GetComControlInHWND(hWnd)

Parameters

Return Value

ErrorLevel

Remarks

WS_Initialize() does not need to be called before calling this function.

Related

WS_GetHWNDofComControl, WS_AttachComControlToHWND

Example

    ; see WS_CreateComControlContainer example

WS_AttachComControlToHWND

Description

Attaches a COM control object to an existing COM control container.

Usage

WS_AttachComControlToHWND(pObject, hWnd)

Parameters

Return Value

(Boolean) True on success, False on failure.

ErrorLevel

Remarks

Attaches a COM control object to a COM control container created using WS_CreateComControlContainer() function.

WS_Initialize() does not need to be called before calling this function.

Related

WS_GetComControlInHWND, WS_GetHWNDofComControl

Example

    ; Creates a WYSIWYG html editor in just 20 lines (method 1)
    #Include ws4ahk.ahk
    WS_Initialize()
    WS_InitComControls()
    
    Gui, +LastFound
    Gui, Show, w800 h600 Center, DhtmlEdit Test
    hWnd := WinExist()
    COMhWnd := WS_CreateComControlContainer(hWnd, 10, 10, 780, 580)
    ppvDEdit := WS_CreateObject("DhtmlEdit.DhtmlEdit")
    WS_AttachComControlToHWND(ppvDEdit, COMhWnd) 
    WS_AddObject(ppvDEdit, "DHtmlControl")
    ; the scripting environment has the object, so we don't need it anymore
    WS_ReleaseObject(ppvDEdit)
    WS_Exec("DHtmlControl.LoadUrl %s", "http://www.autohotkey.com")
    Return
    
    GuiClose:
        Gui, %A_Gui%:Destroy
        WS_UninitComControls()
        WS_Uninitialize()
        ExitApp

WS_CreateComControlContainer

Description

Create a control on a window that will host a COM control object.

Usage

WS_CreateComControlContainer(hWnd, X, Y, Width, Height [, sProgIDorClassID ] )

Parameters

Return Value

ErrorLevel

Set to the DllCall() result.

Remarks

WS_InitComControls must be called before calling this function.

If a valid sProgIDorClassID is supplied, a COM control object will automatically be created in the COM control container. Use WS_GetComControlInHWND to retrieve the associated COM object.

If sProgIDorClassID is not supplied, then the COM control container will not initially have an associated COM control. Use WS_AttachComControlToHWND() to add a COM control object to the COM control container.

WS_Initialize() does not need to be called before calling this function.

Related

WS_InitComControls, WS_AttachComControlToHWND, WS_GetComControlInHWND, WS_GetHWNDofComControl

Example

    ; Creates a WYSIWYG html editor in just 20 lines (method 2)
    #Include ws4ahk.ahk
    WS_Initialize()
    WS_InitComControls()
    
    Gui, +LastFound
    Gui, Show, w800 h600 Center, DhtmlEdit Test
    hWnd := WinExist()
    COMhWnd := WS_CreateComControlContainer(hWnd, 10, 10, 780, 580, "DhtmlEdit.DhtmlEdit")
    ppvDEdit := WS_GetComControlInHWND(COMhWnd)
    WS_AddObject(ppvDEdit, "DHtmlControl")
    ; the scripting environment has the object, so we don't need it anymore
    WS_ReleaseObject(ppvDEdit)
    WS_Exec("DHtmlControl.LoadUrl %s", "http://www.autohotkey.com")
    Return
    
    GuiClose:
        Gui, %A_Gui%:Destroy
        WS_UninitComControls()
        WS_Uninitialize()
        ExitApp