Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

COM Object Reference [AutoHotkey v1.1+]


  • Please log in to reply
233 replies to this topic
jethrow
  • Moderators
  • 2854 posts
  • Last active: May 17 2017 01:57 AM
  • Joined: 24 May 2009

*IMPORTANT: please ask coding questions in the Ask For Help forum

 

Purpose: to create a basic reference for commonly used COM objects.

 

AutoHotkey v1.1+ supports COM natively (thank you Lexikos, Sean, & fincs smile.png ). However, if users don't know or understand any COM objects, this Native COM support is less appealing/useful. Therefore, I am creating this thread as somewhat of a basic COM object reference. Forum members can add a COM object "profile", and I will link it to the original post. Questions are also welcome. Here is the suggested format for the COM Object profile:


COM Object: 
Purpose: 
System Requirements: 
Documentation Link: 
Other Links: 
Basic Code Example: 

NOTE - for the Documentation Link, please provide a link to the method/properties documentation.

See Also: CLSID Registry Scanner - view information about COM/ActiveX components installed on your computer.

COM Object List:


HTML File - Represents an HTML document. Can be used to read, write, & interact with HTML.

InternetExplorer Application - Explore Websites.

MSXML2 DOMDocument 6.0 - XML parser (v6.0 requires XP SP3 or newer - see here for compatability with older XP).

ScriptControl - Dynamically execute VBScript or JScript.

Scripting Dictionary - Object that stores data key, item pairs.

Scripting FileSystemObject - Access Files & Folders

Shell Application - Access Explorer & IE Windows/Tabs; Open & Manipulate Windows.
  Get File Properties - Rename Files/Folders - Unzip a Zip File

Shell Explorer - Embed an Explorer/Browser Control in a Gui (Internet Explorer - Trident Browser)

Speech API: SpVoice - Text-to-Speech (TTS)

VBScript RegExp - VBS Regular Expressions (including global match)

Windows Media Player - Play Media Files; Embed WMPlayer Control in a GUI.

WinHttpRequest - Provides simple HTTP client functionality, allowing much more control than UrlDownloadToFile.

Winmgmt - Get System Information; Manage Windows Services
  Retrieves file & folder properties - Manipulating Services

WScript Shell - Various Administration Tasks (many native AHK tasks)
  Set Volatile Env Variable

 

MS Office Applications


MS Excel - Perform calculations, analyse information and visualize data in spreadsheets
  Range.Value: SafeArray

Excel Workbook - Hold MS Excel Data

MS Outlook - Personal Information Manager
  Read/Write Appt - Create New Items - Access Folders/Items - Send Email w/ Attachments

MS PowerPoint - Create powerpoint presentations

MS Word - Word Processor - create and edit various documents

 

Objects Requiring Additional Files/Installation (see also - Register ActiveX Component)


Ahk.ComSurrogate.32/64 - Create COM objects of a specified bitness.

CAPICOM Series [capicom_dc_sdk.msi] - digitally sign data, sign code, verify digital signatures, envelop data for privacy, hash data, encrypt/decrypt data and more ( 32-bit OS only ).

FooBar2000 [COM Automation Server] - Manipulate the foobar2000 media player.

GFLAx [GflAx.dll - 1.11 MB] - Library to load images and photos easily ( read/write/create/manipulate ... images ).

Google Desktop [Install] - Add Gadgets your desktop, & easily search your computer ( like Google ).
  kongulo plugin

ImageMagick [Install] - Software suite to create, edit, and compose bitmap images. (See here for notes on installation)

Windows Image Acquisition (WIA) Automation [WIAAut.dll - 316 KB] - acquire images on digital cameras/scanners/Web cameras, and rotate/scale/annotate image files.
  (See note regarding WPD Automation Object Model)

XStandard.Zip [XZip.dll - 137 KB] - Zip & Unzip with many features



jethrow
  • Moderators
  • 2854 posts
  • Last active: May 17 2017 01:57 AM
  • Joined: 24 May 2009

... some other COM posts:
 

CDO COM - Email Delivery BAHK_L

WMI Tasks COM with AHK_L

Create a scheduled task natively AHK_L

AHK_L ComDispatch v1.0

Controlling Synaptics Touchpad using Synaptics COM API

 
Retrieve file path of the selected file

Explorer_GetSelection(hwnd="") {
   WinGet, process, processName, % "ahk_id" hwnd := hwnd? hwnd:WinExist("A")
   WinGetClass class, ahk_id %hwnd%
   if (process = "explorer.exe")
      if (class ~= "Progman|WorkerW") {
         ControlGet, files, List, Selected Col1, SysListView321, ahk_class %class%
         Loop, Parse, files, `n, `r
            ToReturn .= A_Desktop "\" A_LoopField "`n"
      }
      else if (class ~= "(Cabinet|Explore)WClass") {
         for window in ComObjCreate("Shell.Application").Windows
            if (window.hwnd==hwnd)
               sel := window.Document.SelectedItems
         for item in sel
            ToReturn .= item.path "`n"
      }
   return Trim(ToReturn,"`n")
}


jethrow
  • Moderators
  • 2854 posts
  • Last active: May 17 2017 01:57 AM
  • Joined: 24 May 2009

COM Object: Scripting.Dictionary

Purpose: Object that stores data key, item pairs.

System Requirements: General

Documentation Link: Dictionary Object

Other Links:

Basic Code Example:

 

sd := ComObjCreate("Scripting.Dictionary")

;// Add Items
sd.Add("Name", "AutoHotkey")
sd.Add("Abv", "AHK")
sd.Item("URL") := "www.autohotkey.com"

;// Get Item
MsgBox, , Get Key, % "Name = " sd.item("Name")

;// Get Number of Items
MsgBox, , Item Count, % "Total Items: " sd.Count

;// Check for Key Existance
MsgBox, , Key Exist?
	, % "Abv Exist: " sd.Exists("Abv") "`n"
	. "Test Exist: " sd.Exists("Test")

;// Remove a Key
sd.Remove("Abv")
MsgBox, , Removed: "Abv", % "Abv Exist: " sd.Exists("Abv")

;// Enumerate Keys
for Key in sd
	list .= Key " = " sd.item(Key) "`n"
MsgBox, , Enumerated Keys, %list%

;// Clear the Dictionary
sd.RemoveAll()
MsgBox, , Removed All Keys, % "Total Items: " sd.Count

 

... what can Scripting.Dictionary do that the built-in objects can't do?

Great question - Case Sensitive Keys & Enumerating Keys in Order of Creation (natively):

sd := ComObjCreate("Scripting.Dictionary")

;// Case Sensitive Keys
sd.item("ahk") := "autohotkey"
sd.item("AHK") := "AutoHotkey"
MsgBox % sd.item("ahk") "`n" sd.item("AHK")

sd.RemoveAll()

;// Enumerate Keys in Order of Creation
Loop, 5
	sd.item(6-A_Index) := "Value " A_Index
for key in sd
	t .= key " = " sd.item(key) "`n"
MsgBox %t%

 

Related: How make Associative array keys case sensitive



guest3456
  • Guests
  • Last active:
  • Joined: --
this is execellent, i know nothing of COM so please teach me in this thread :)

guest3456
  • Guests
  • Last active:
  • Joined: --
and i assume the same Scripting.Dictionary can be done in regular AHK? perhaps you should post both vanilla and _L code?

fincs
  • Moderators
  • 1662 posts
  • Last active:
  • Joined: 05 May 2007
Vanilla is not supported here, it's an AutoHotkey_L-only thread.
It is strongly recommended that you use AutoHotkey_L for COM tasks.

jethrow
  • Moderators
  • 2854 posts
  • Last active: May 17 2017 01:57 AM
  • Joined: 24 May 2009

...perhaps you should post both vanilla and _L code?

One of the main reasons COM seems so confusing, IMO, is because of the syntax that was required with Vanilla AHK. However, with Native COM support in AutoHotkey_L, COM has a more natural syntax. Therefore, I'm going to refrain from posting Vanilla AHK syntax in this thread to minimalize confusion & lessen the learning curve. However, there are several posts throughout the forums. Here's one both Lexikos and Sean participated in: Arrays using ws4ahk, & Dictionary\Array Objects

@fincs - thanks for the input, and thanks for helping in the development of AHK w/ Native COM Support :D

Lexikos
  • Administrators
  • 9844 posts
  • AutoHotkey Foundation
  • Last active:
  • Joined: 17 Oct 2006

More importantly, what can Scripting.Dictionary do that the built-in objects can't do?

COM Object: WinHttpRequest
Purpose: Provides simple HTTP client functionality, allowing much more control than UrlDownloadToFile.
System Requirements: General*
Documentation Link: <!-- m -->http://msdn.microsof...y/aa384106.aspx<!-- m -->
Basic Code Example:

WebRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1")
WebRequest.Open("GET", "http://www.autohotkey.net/~Lexikos/AutoHotkey_L/docs/AHKL_ChangeLog.htm")
WebRequest.Send()
RegExMatch(WebRequest.ResponseText, "(?<=<h2>).*?(?=</h2>)", ver)
MsgBox % ver
WebRequest := ""

* Note MSDN says Windows 2000 or later required, but I've seen some other cases where this wasn't accurate; maybe they say that since they really don't support older versions of Windows. Furthermore, AutoHotkey_L requires Windows 2000 or later.

Btw, perhaps the wiki is a good place to put this reference (without the discussion).



jethrow
  • Moderators
  • 2854 posts
  • Last active: May 17 2017 01:57 AM
  • Joined: 24 May 2009

... what can Scripting.Dictionary do that the built-in objects can't do?

This is an extremely good point. The main reason included it is for an example of using COM, since it's such a simple object.

... perhaps the wiki is a good place to put this reference (without the discussion).

I had thought about this too - perhaps we could do that as well. However, I was hoping to create somewhat of a learning environment where users could learn COM by creating an object "profile" with examples. My plan is to link multiple posts for each object back to the original post - especially for objects such as the MS Office Applications.

BTW - Thank You for the continued effort on developing AutoHotkey_L! :D

jethrow
  • Moderators
  • 2854 posts
  • Last active: May 17 2017 01:57 AM
  • Joined: 24 May 2009

COM Object: HTMLFile

Purpose: Represents an HTML document. Can be used to read, write, & interact with HTML.

System Requirements: General

Documentation Link:  document object

Other Links: W3Schools - Document Object

Basic Code Example - this example extracts all the text & URLs from the links on the Google Search Page:

;// download the webpage source
URLDownloadToFile, http://www.google.com, Google_HTML
FileRead, html, Google_HTML
FileDelete, Google_HTML

;// write the Google Source to an HTMLfile
document := ComObjCreate("HTMLfile")
document.write(html)

;// loop through all the links
links := document.links
while (A_Index<=links.length, i:=A_Index-1)
   list .= i ") " links[i].innerText "`nURL: " links[i].href "`n`n"

;// some URLs have "about:" rather than the domain
StringReplace, list, list, about:, http://www.google.com, All

MsgBox, %list%


This next example shows how an HTMLfile object* can be used to create an HTML Control:

color := HtmlBgColor()

;// HTML to be added to a GUI:
html =
(
   <body style='background-color:%color%;overflow:auto'>
      <span id='id' style='color:black'>text color</span> example
   </body>
)

;// create a simple GUI
Gui, Add, Button, x6 y60 w55 h20, Red
Gui, Add, Button, x71 y60 w55 h20, Blue
Gui, Add, ActiveX, x0 y-5 w140 h50 vdocument, HTMLFile
document.write(html)
Gui, Show, x399 y246 w138 h86, HTML
return

GuiClose:
   Gui, Destroy
   ExitApp
ButtonRed:
ButtonBlue:
   document.all("id").style.color := SubStr(A_ThisLabel,7)
   return

HtmlBgColor() {
   Format := A_FormatInteger
   SetFormat, IntegerFast, Hex
   color := SubStr(DllCall("GetSysColor", "int",15),3)
   SetFormat, IntegerFast, %Format%
   return SubStr(color,5,2) SubStr(color,3,2) SubStr(color,1,2) ;// switch from BGR -> RGB
}

*Note - the HTMLfile object isn't required to accomplish this. You could simply write the HTML when adding the ActiveX Control:

Gui, Add, ActiveX, x0 y-5 w140 h50 vDocument, MSHTML:%html%

This post has an example of a completely HTML based GUI.



tank
  • Administrators
  • 4345 posts
  • AutoHotkey Foundation
  • Last active: May 02 2019 09:16 PM
  • Joined: 21 Dec 2007
FYI Jethrow
I dont know if your aware but creating a htmldocument can also cause code to be live. Javascript executes any how. some window objects may not but its handy from a urldownloadtofile fileread standpoint for dynamic content :wink:
Never lose.
WIN or LEARN.

lexios
  • Guests
  • Last active:
  • Joined: --

... htmldocument can also cause code to be live.

The keyword here is "can", i.e. it only happens on some systems.

olfen
  • Members
  • 115 posts
  • Last active: Dec 25 2012 09:48 AM
  • Joined: 04 Jun 2005

GFL SDK is a library to load/save easily graphics formats.

It has the features :

Import about 100 graphic file formats
Export about 40 graphic file formats
Support of 10/12/16bits per component
Color mode convert
Lut transforms (brightness, contrast, ...)
Filters (blur, average, ...)
Tools (resize, de-interlace, ...)
Multi-page file creation
JPEG lossless transform
EXIF reading (with or without loading picture)
IPTC reading/writting (with or without loading picture)
And many may other things...

GFL SDK is provided as FREEWARE for private non-commercial or educational use (including non-profit organization)

[*:1clakve5]COM Object: GflAx[*:1clakve5]Purpose: Library to load images and photos easily.[*:1clakve5]Documentation Link: <!-- m -->http://www.xnview.com/en/gfl.html<!-- m --> ; methods and properties are documented in the help file that comes with the installer.[*:1clakve5]System Requirements: GFLAx (ActiveX/ASP component) v2.80[*:1clakve5]Basic Code Example:
oG := ComObjCreate("GflAx.GflAx") ; create GflAx object
oG.SaveFormatName := "tiff"       ; save image in Tagged Image File Format

w := 600, h := 420                ; set width and height of new image
oG.NewBitmap(w, h, 0x0)           ; create new bitmap 

oG.LineWidth := 4                 ; set linewidth to 4
oG.LineColor := 0xB0CD7D          ; set linecolor to 0xB0CD7D (BGR-Format)

; Vertex contains a list of x\y-coordinates for use with AddVertex, DrawPolyLine and FreeVertex.
; Of course this list can be created dynamically in practical use.
Vertex := "0,240|25,240|29,210|42,269|56,225|62,240|117,240|137,190|158,269|167,217|170,240|233,240|"
. "248,179|267,270|281,218|288,240|354,240|372,176|390,259|402,220|408,240|458,240|487,118|530,319|552,185|"
. "565,240|600,240"

Loop, parse, Vertex, |            
{
  StringSplit, v, A_LoopField, `,
  oG.AddVertex(v1, v2)            ; add separate coordinates to the vertex list
} 

oG.DrawPolyLine                   ; draw a polyline from the vertex list
oG.FreeVertex                     ; free the vertex list

oG.FillColor := 0xB0CD7D          ; set fillcolor to 0xB0CD7D (BGR-Format)
oG.DrawFillCircle(598, 240, 3)    ; draw a filled cricle
oG.GaussianBlur(0.6)              ; blur image
oG.SaveBitmap("Line")             ; save image

r1 := 30, r2 := 15                ; define width\height for columns\rows of grid
oG.NewBitmap(w, h, 0x004037)      ; create new bitmap with background-color
                                  ; 0x004037 (BGR-Format)

oG.LineWidth := 1                 ; set linewidth to 1
oG.LineColor := 0x054D3F          ; set linecolor to 0x054D3F (BGR-Format)
xy := 0
Loop, % w/r2 - 1
  xy += r2, oG.DrawLine(xy, 0, xy, h), oG.DrawLine(0, xy, w, xy)  ; Draw grid

oG.LineWidth := 1                 ; set linewidth to 1
oG.LineColor := 0x32824D          ; set linecolor to 0x32824D (BGR-Format)
xy := 0
Loop, % w/r1 - 1
  xy += r1, oG.DrawLine(xy, 0, xy, h), oG.DrawLine(0, xy, w, xy) ; Draw grid

oG.SaveBitmap("Grid")             ; save image

; Merge Grid.tif and Line.tif                                                                         
oG.MergeAddFile("Grid.tif", 50, 0 ,0)
oG.MergeAddFile("Line.tif", 50, 0 ,0)
oG.Merge
oG.MergeClear

; set font properties
oG.FontName := "Arial"
oG.FontSize := 24
oG.FontBold := true

; draw the text
oG.TextOut("AHK_L", 30, 30, 0x0000ff)
oG.SaveBitmap(A_ScriptName)

ObjRelease(oG)                    ; release object


jethrow
  • Moderators
  • 2854 posts
  • Last active: May 17 2017 01:57 AM
  • Joined: 24 May 2009

NOTE: On Windows 7, regsvr32.exe must be run as the Administrator

Olfen - thanks for the post - I've been wanting to learn more about drawing & creating images using AHK happy.png . Could you modify your post though? This example seems to require the GFL ActiveX Component (GflAx.dll) - which needs to be registered on the computer. The following script shows how this process can be automated ( requires DLL file: GlfAx.dll )


;// Register ActiveX Component
RunWait, REGSVR32 /s GflAx.dll ; assuming DLL is in the Script Directory


;// ... Run Code ...


;// Unregister ActiveX Component
RunWait, REGSVR32 /u /s GflAx.dll

If some other users could help me out -- is it suspicious at all for a script/program to register it's own ActiveX Component -- or is this normal?

EDIT - Also, you can check if an ActiveX Component is Registered based on the ProgID (GflAx.GflAx) by checking the Registry:

RegRead, D, HKCR, GflAx.GflAx
if Errorlevel ; or If D =
MsgBox, DLL Not Registered
else
MsgBox, DLL is Registered


jethrow
  • Moderators
  • 2854 posts
  • Last active: May 17 2017 01:57 AM
  • Joined: 24 May 2009

COM Object: ScriptControl

Purpose: Dynamically execute VBScript or JScript

NOTE: Many VBScript & JScript scripts can be translated to AHK, rather than using the ScriptControl object. (see the last example)

System Requirements: 32bit AHK (see here for 64bit compatability)

Documentation Link: Using the ScriptControl

Code Examples:

 

The first example will execute some basic VBScript:

sc := ComObjCreate("ScriptControl")

;// define the Language
sc.Language := "VBScript"

;// define the VBScript
script =
(
Dim string
Arr = Array("Auto", "Hot", "key!")
For Each i In Arr
   string = string & i
Next
MsgBox "Joined Array Elements:" & vbCR & string, 64, "VBScript MsgBox"
)

;// execute the VBScript
sc.ExecuteStatement(script)

;// extract values from the VBScript
MsgBox, 64, AutoHotkey MsgBox, % "Joined Array Elements:`n" sc.Eval("Arr(0) & Arr(1) & Arr(2)")


The next example will execute some basic JScript:

sc := ComObjCreate("ScriptControl")

;// define the Language
sc.Language := "JScript"

;// define the JScript
script =
(
string = '';
obj = { 'Name':'AutoHotkey', 'URL':'www.AutoHotkey.com', 'Color':'Green' };
for (i in obj)
   string += i + ' = ' + obj[i] + '\n';
)

;// execute the JScript
sc.ExecuteStatement(script)

;// extract a value from the JScript
MsgBox, 0, JScript Variable "string":, % sc.Eval("string")

;// extract an Object from the JScript
obj := sc.Eval("obj")
MsgBox, 0, Elements from the JScript Object:, % "Name: " obj.Name "`nURL: " obj.URL


This next example will execute JScript, which will execute VBScript:

sc := ComObjCreate("ScriptControl")

;// define the Language
sc.Language := "JScript"

;// define the JScript
script =
(
sc = new ActiveXObject('ScriptControl');
sc.Language = "VBScript";

script = 'MsgBox "VBScript in JScript in AutoHotkey", 48, "Embedded ScriptControls"';
sc.ExecuteStatement(script);
)

;// execute the JScript -> which executes VBScript
sc.ExecuteStatement(script)

NOTE: The following 3 scripts are equivalent:

;// AHK:
wb := ComObjCreate("InternetExplorer.Application")
wb.Navigate("http://www.autohotkey.com/forum/viewtopic.php?t=61509")
wb.Visible := True
while wb.Busy
   Sleep, 100
MsgBox, % "WebPage Loaded: " wb.Document.title

;// VBScript:
Set wb = CreateObject("InternetExplorer.Application")
wb.Navigate "http://www.autohotkey.com/forum/viewtopic.php?t=61509"
wb.Visible = True
While wb.Busy
   WScript.Sleep 100
WEnd
MsgBox "WebPage Loaded: " & wb.Document.title

;// JScript:
wb = new ActiveXObject("InternetExplorer.Application")
wb.Navigate("http://www.autohotkey.com/forum/viewtopic.php?t=61509")
wb.Visible = 1
while (wb.Busy)
   WScript.Sleep(100)
WScript.Echo("WebPage Loaded: " + wb.Document.title)