COM Object Reference

Post your working scripts, libraries and tools
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

COM Object Reference

01 Oct 2013, 23:35

This is a rebuild of the original COM Object Reference thread, minus the tangential discussions. Please keep an eye out for any potential code improvements to keep this repository up to date with the latest AHK changes.

jethrow's original opening post:

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

AutoHotkey now supports COM natively (thank you Lexikos, Sean, & fincs :) ). This doesn't eliminate the COM Standard Library, but it does add quite a bit of functionality to AutoHotkey. 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 BBCode for the COM obj profile:

Code: Select all

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.
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

01 Oct 2013, 23:38

Retrieve file path of the selected file

Code: Select all

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")
}
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

01 Oct 2013, 23:43

COM Object: Scripting.Dictionary
Purpose: Object that stores data key, item pairs.
System Requirements: General
Documentation Link: Dictionary Object
Other Links:
Basic Code Example:

Code: Select all

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 Existence
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):

Code: Select all

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
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

01 Oct 2013, 23:45

COM Object: WinHttpRequest
Purpose: Provides simple HTTP client functionality, allowing much more control than UrlDownloadToFile.
System Requirements: General*
Documentation Link: http://msdn.microsoft.com/en-us/library/aa384106.aspx
Basic Code Example:

Code: Select all

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.
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

01 Oct 2013, 23:49

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:

Code: Select all

;// 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:

Code: Select all

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:

Code: Select all

Gui, Add, ActiveX, x0 y-5 w140 h50 vDocument, MSHTML:%html%
This post has an example of a completely HTML based GUI.
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

01 Oct 2013, 23:56

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)
COM Object: GflAx
Purpose: Library to load images and photos easily.
Documentation Link: http://www.xnview.com/en/gfl.html ; methods and properties are documented in the help file that comes with the installer.
System Requirements: GFLAx (ActiveX/ASP component) v2.80
Basic Code Example:

Code: Select all

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
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 08:56

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:

Code: Select all

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:

Code: Select all

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:

Code: Select all

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:

Code: Select all

;// 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)
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 09:03

COM Object: Microsoft Outlook
Purpose: Read and Write Appointments from calendar
System Requirements: Microsoft Outlook: tested with 2010 and 2007
Documentation: http://support.microsoft.com/kb/220595
Other Links: following is a translation of this vb.net script.

Code: Select all

olFolderCalendar :=	9   ; Outlook.OlDefaultFolders.olFolderContacts
olFolderContacts :=	10  ; get constants from visual studio
olAppointmentItem = 1
                        
profileName :=	"Outlook"
Outlook :=	ComObjCreate("Outlook.Application")
namespace :=	Outlook.GetNamespace("MAPI")
namespace.Logon(profileName)  
calendar :=	namespace.GetDefaultFolder(olFolderCalendar)
items :=	calendar.Items
count :=	items.Count
msgbox %	"calendar items: " count
item :=	calendar.Items(1)
item1 :=	"subject: " item.Subject . "`n"
item1 .=	"Start: " item.Start . "`n"
item1 .=	"Duration: " item.Duration . "`n"
item1 .=	"Body: " item.Body "`n"
msgbox %	"item1" item1
date :=	"9/1/2010 9:00:00 AM"	; this works, although the recommended
				; format is year/month/date
				; hours:minutes:seconds AM/PM

date :=	"2010/9/1 9:00:00 AM"
msgbox %	makeAppointment(Outlook, "auto", "autohotkey rocks", date, "60", "2")

!r::reload
!q::exitapp

makeAppointment(outlook, subject, body, startTime, duration, busyStatus)
{
	static	olAppointmentItem = 1
	 , olFree = 0
	 , olTentative = 1
	 , olBusy = 2
	 , olOutOfOffice = 3
	item :=	outlook.CreateItem(olAppointmentItem)
	item.Body :=	body
	item.BusyStatus :=	busyStatus ; olBusy
	msgbox %	startTime
	item.Start :=	startTime ; 9/1/2010 9:00:00 AM
	item.Duration :=	duration ; 60
	item.Subject :=	subject
	return	item.save()  ; warns about programmatic access with normal settings
}
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 09:07

COM Object: Google Desktop
Purpose: manually feed items for google desktop to index
System Requirements: Google Desktop
Documentation Link: http://code.google.com/apis/desktop/docs/indexapi.html
Other Links: following is a translation of this python plugin: kongulo.

Code: Select all

registerAhkIndexer()
Loop, %A_ScriptDir%\*.ahk
{
	FileRead, content, %A_LoopFileFullPath%
	gdsIndex(A_LoopFileFullPath, content)
	tooltip, %A_LoopFileFullPath%
}
return

variantDate(time)
{
	beginning :=	"18991230"
	now :=	time ; A_YYYY . A_MM . A_DD
	EnvSub, now, beginning, days
	stringtrimleft, hours, time, 8
	stringleft, hours, hours, 2
	fraction :=	hours / 24
	now :=	now . fraction

	VT_DATE :=	0x0007
	vnow :=	ComObjParameter(VT_DATE, now)
	return	vnow
}


gdsIndex(uri, content)
{
	global	_GUID
	static	eventFactory

	if	!eventFactory
		eventFactory :=	comobjcreate("GoogleDesktopSearch.EventFactory")

	event :=	eventFactory.CreateEvent(_GUID, "Google.Desktop.File")
	time :=	variantDate(A_Now)
	event.AddProperty("format", "text/plain")
	event.AddProperty("content", content)
	event.AddProperty("uri", uri)
	event.AddProperty("last_modified_time", time)
	event.Send(0x01)
}


registerAhkIndexer()
{
	global	_GUID
	oSC :=	ComObjCreate("ScriptControl")
	oSC.Language :=	"JScript"
	script =
	(
	obj = ['Title', 'ahkKongulo', 'Description', 'A simple ahk indexer', 'Icon', 'c:\windows\system32\SHELL32.dll,134' ];
	)
	oSC.ExecuteStatement(script)
	obj :=	oSC.Eval("obj")

	_GUID :=	"{D8FCC944-C8E9-4E56-83E7-61FC30D98E2B}" ; generate your own please
	gds :=	comobjcreate("GoogleDesktopSearch.Register")
	ComObjError(False) ; ignore reregistration error
	gds.RegisterIndexingComponent(_GUID, obj)
	ComObjError(True)
}

unregisterAhkIndexer()
{
	_GUID :=	"{D8FCC944-C8E9-4E56-83E7-61FC30D98E2B}"
	gds :=	comobjcreate("GoogleDesktopSearch.Register")
	gds.UnRegisterIndexingComponent(_GUID)
}
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 09:53

COM Object: InternetExplorer.Application
Purpose: Explore Websites
System Requirements: General
Documentation Link: Reference for Developers
Other Links: NavConstants, CMD IDs, Basic Webpage Controls
Code Example:

Code: Select all

;// open Standard Internet Explorer
wb :=	ComObjCreate("InternetExplorer.Application") ;// create IE
wb.Visible :=	true ;// show IE
wb.GoHome() ;// Navigate Home

;// the ReadyState will be 4 when the page is loaded
while	wb.ReadyState <> 4
	continue

;// get the Name & URL of the site
MsgBox %	"Name: " wb.LocationName
	 . "`nURL: " wb.LocationURL
	 . "`n`nLet's Navigate to Autohotkey.com..."

;// get the Document - which is the webpage
document :=	wb.document
	
;// Navigate to AutoHotkey.com
wb.Navigate("www.AutoHotkey.com") ;// 2nd param - see NavConstants

;// the Busy property will be true while the page is loading
while	wb.Busy
	continue
MsgBox Page Loaded...Going Back Now

;// Go Back
wb.GoBack()

while	wb.Busy
	continue
MsgBox The page is loaded - now we will refresh it...

;// Refresh the page
wb.Refresh()
while	wb.Busy
	continue
MsgBox Now that the page is Refreshed, we will Select All (^a)...

;// Execute Commands with ExecWB()
SelectAll :=	17 ;// see CMD IDs
wb.ExecWB(SelectAll,0) ;// second param as "0" uses default options

Sleep 2000
MsgBox Now that we are done, we will exit Interent Explorer

;// Quit Internet Explorer
wb.Quit()
Note - Internet Explorer uses the iWebBrowser2 interface
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 09:55

COM Object: Shell.Application
Purpose: Access Explorer & IE Windows/Tabs; Open & Manipulate Windows
System Requirements: General
Documentation Link: Shell Object
Other Links: ShellWindows Collection
Code Example:

The Windows Property returns the ShellWindows Collection, which is extremely helpful for accessing Explorer/IE Windows. This example Enumerates all the Explorer & IE Windows/Tabs:

Code: Select all

SetFormat, IntegerFast, Hex ;// display HWND in Hex

for Item in ComObjCreate("Shell.Application").Windows ;// loop through the ShellWindows Collection
	data .=	"Name:`t" Item.LocationName "`n"
	 . "URL:`t"   Item.LocationURL "`n"
	 . "Prog:`t"  Item.Name "`n"
	 . "`t"       Item.FullName "`n"
	 . "HWND:`t"  Item.HWND "`n`n"

MsgBox %data%
Several of the methods/properties for the Shell.Application object are simple to do with AHK's commands - such as showing certain Dialog boxes or Minimizing all windows. However, here are a few examples for moving windows around:

Code: Select all

shell :=	ComObjCreate("Shell.Application")

MsgBox Cascade Windows
shell.CascadeWindows()
Sleep 2000

MsgBox Tile Windows Horizontally
shell.TileHorizontally()
Sleep 2000

MsgBox Tile Windows Vertically
shell.TileVertically()
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 09:59

COM Object: MSXML2.DOMDocument.6.0
Purpose: XML parser
System Requirements: Windows XP SP3, Vista, 7
Documentation Link: MSDN
Other Links: A Beginner's Guide to the XML DOM
Basic Code Example:

Code: Select all

xmldata =
(
	<?xml version="1.0"?>
	<compactdiscs>
	<compactdisc>
	<artist type="individual">Frank Sinatra</artist>
	<title numberoftracks="4">In The Wee Small Hours</title>
	<tracks>
	<track>In The Wee Small Hours</track>
	<track>Mood Indigo</track>
	<track>Glad To Be Unhappy</track>
	<track>I Get Along Without You Very Well</track>
	</tracks>
	<price>$12.99</price>
	</compactdisc>
	<compactdisc>
	<artist type="band">The Offspring</artist>
	<title numberoftracks="5">Americana</title>
	<tracks>
	<track>Welcome</track>
	<track>Have You Ever</track>
	<track>Staring At The Sun</track>
	<track>Pretty Fly (For A White Guy)</track>
	</tracks>
	<price>$12.99</price>
	</compactdisc>
	</compactdiscs>
)

doc :=	loadXML(xmldata)

; XPath
msgbox %	doc.selectSingleNode("/compactdiscs/compactdisc[artist=""Frank Sinatra""]/title").text

; Manually retrieving nodes and values
msgbox %	DisplayNode(doc.childNodes)

DisplayNode(nodes, indent=0)
{
	for node in nodes
	{
		if	node.nodeName != "#text"
			text .=	spaces(indent) node.nodeName ": " node.nodeValue "`n"
		else	text .=	spaces(indent) node.nodeValue "`n"
		if	node.hasChildNodes
			text .=	DisplayNode(node.childNodes, indent+2)
	}
	return	text
}

spaces(n)
{
	Loop, %n%
		t .=	" "
	return	t
}

loadXML(ByRef data)
{
	o :=	ComObjCreate("MSXML2.DOMDocument.6.0")
	o.async :=	false
	o.loadXML(data)
	return	o
}
This renders xpath() obsolete, except for vanilla scripts or Win2000 scripts.
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 10:04

COM Object: SAPI.SpVoice
Purpose: Text-to-Speech
System Requirements: General
Documentation Link: SpVoice Interface
Code Example:

Code: Select all

Text :=	"Hello World!"

SAPI :=	ComObjCreate("SAPI.SpVoice")
MsgBox,, Rate: 0, Speak the Text
SAPI.speak(Text)

MsgBox,, Rate: -7, Slow down the Speech
SAPI.rate :=	-7
SAPI.speak(Text)

MsgBox,, Rate: 7, Speed up the Speech
SAPI.rate :=	7
SAPI.speak(Text)

SAPI.rate :=	0 ;// set to default rate

MsgBox,, Volume: 50, Lower the Volume (ranges 0-100)
SAPI.volume :=	50
SAPI.speak(Text)
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 10:08

COM Object: ImageMagickObject COM+ Object
Purpose: ImageMagick® is a software suite to create, edit, and compose bitmap images.
System Requirements: ImageMagickObject COM+ Object
Documentation Link:
Other Links: http://www.imagemagick.org/script/binar ... hp#windows
Basic Code Example:

Code: Select all

oI :=	ComObjCreate("ImageMagickObject.MagickImage.1") 

imgs :=	Object() 
	
Loop, 16 { 
	filename :=	"plasma" . A_Index . ".jpg" 
	oI.convert("-size", "200x200", "plasma:", filename) 
	imgs.Insert(filename)    
} 

imgs.Insert("montage.jpg")    
stitch(oI, imgs*) 

stitch(obj, params*) { 
	obj.montage("-geometry", "+0+0", params*) 
} 

oI.convert("montage.jpg", "-verbose", "info:image_info.txt") 
oI.convert("montage.jpg", "-define", "histogram:unique-colors=false", "histogram:histogram.gif") ; create histogram
FileRead, info, image_info.txt 
FileDelete, image_info.txt 
MsgBox % info
Convert image to text:

Code: Select all

oI :=	ComObjCreate("ImageMagickObject.MagickImage.1") 
oI.convert("montage.jpg", "montage.txt")
Output:

Code: Select all

# ImageMagick pixel enumeration: 40,40,255,rgb 
0,0: (235,241,255)  #EBF1FF  rgb(235,241,255) 
1,0: (221,242,237)  #DDF2ED  rgb(221,242,237) 
2,0: (219,253,226)  #DBFDE2  rgb(219,253,226) 
3,0: (192,225,208)  #C0E1D0  rgb(192,225,208) 
4,0: (202,224,237)  #CAE0ED  rgb(202,224,237) 
5,0: (223,232,255)  #DFE8FF  rgb(223,232,255) 
6,0: (224,220,245)  #E0DCF5  rgb(224,220,245) 
7,0: (240,223,239)  #F0DFEF  rgb(240,223,239) 
8,0: (255,240,251)  #FFF0FB  rgb(255,240,251) 
9,0: (244,253,255)  #F4FDFF  rgb(244,253,255) 
10,0: (188,228,230)  #BCE4E6  rgb(188,228,230) 
11,0: (192,239,245)  #C0EFF5  rgb(192,239,245) 
12,0: (209,236,255)  #D1ECFF  rgb(209,236,255) 
13,0: (232,235,255)  #E8EBFF  rgb(232,235,255) 
14,0: (235,237,255)  #EBEDFF  rgb(235,237,255) 
15,0: (213,225,237)  #D5E1ED  rgb(213,225,237) 
16,0: (230,237,245)  #E6EDF5  rgb(230,237,245) 
17,0: (230,249,255)  #E6F9FF  rgb(230,249,255) 
...
Get information about a single pixel of an image:

Code: Select all

; http://www.imagemagick.org/script/fx.php 
oI :=	ComObjCreate("ImageMagickObject.MagickImage.1") 
r :=	oI.identify("-format", "%[fx]", "montage.jpg") 
MsgBox %	r
Notes:
I sometimes need to automatically stitch images together.
I used GflAx previously, but there had to calculate canvas size and positioning myself.
Now ImageMagick does the job for me.

The scope of ImageMagick is endless. Explore!
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 10:11

COM Object: Word.Application
Purpose: create and edit various documents
System Requirements: Microsoft Office Word application
Documentation Link: http://msdn.microsoft.com/en-us/library/bb148369
Other Links:
Basic Code Example:

Code: Select all

oWord :=	ComObjCreate("Word.Application") ; create MS Word object
oWord.Documents.Add ; create new document

oWord.Selection.Font.Bold :=	1 ; bold
oWord.Selection.TypeText("Visit ") ; type text
oWord.ActiveDocument.Hyperlinks.Add(oWord.Selection.Range, "http://www.autohotkey.com/forum/topic61509.html","","","COM Object Reference [AutoHotkey_L]") ; insert hyperlink
oWord.Selection.TypeText("and learn how to work with ") ; type text
oWord.Selection.Font.Italic :=	1 ; italic
oWord.Selection.TypeText("COM objects") ; type text
oWord.Selection.Font.Bold :=	0, oWord.Selection.Font.Italic :=	0 ; bold and italic off
oWord.Selection.TypeText(".") ; type text
oWord.Selection.TypeParagraph ; type paragraph (enter, new line)

oWord.Visible :=	1, oWord.Activate ; make it visible and activate it.
ExitApp
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 10:14

COM Object: Excel.Application
Purpose: Perform calculations, analyse information and visualise data in spreadsheets.
System Requirements: Microsoft Office Excel application
Documentation Link: http://msdn.microsoft.com/en-us/library/bb149067
Other Links:
Basic Code Example:

Code: Select all

oExcel :=	ComObjCreate("Excel.Application") ; create Excel Application object
oExcel.Workbooks.Add ; create a new workbook (oWorkbook :=	oExcel.Workbooks.Add)

oExcel.Range("A1").Value :=	3 ; set cell A1 to 3
oExcel.Range("A2").Value :=	7 ; set cell A2 to 7
oExcel.Range("A3").Formula :=	"=SUM(A1:A2)" ; set formula for cell A3 to SUM(A1:A2)

oExcel.Range("A1:A3").Interior.ColorIndex :=	19 ; fill range of cells from A1 to A3 with color number 19
oExcel.Range("A3").Borders(8).LineStyle :=	1 ; set top border line style for cell A3 (xlEdgeTop = 8, xlContinuous = 1)
oExcel.Range("A3").Borders(8).Weight :=	2 ; set top border weight for cell A3 (xlThin = 2)
oExcel.Range("A3").Font.Bold :=	1 ; set bold font for cell A3

A1 :=	oExcel.Range("A1").Value ; get value from cell A1, and store it in A1 variable
oExcel.Range("A4").Select ; select A4 cell
oExcel.Visible :=	1 ; make Excel Application visible
MsgBox %	A1 "`n" oExcel.Range("A2").Value ; check. You can use Round() function to round numbers to the nearest integer
ExitApp
How to access Workbook without opening it?

Code: Select all

FilePath :=	"C:\Book1.xlsx" ; example path
oWorkbook :=	ComObjGet(FilePath) ; access Workbook object
MsgBox %	oWorkbook.Sheets(1).Range("A1").Value ; get value from A1 cell in first sheet
How to access active Excel Application object?

Use oExcel := Excel_Get(), not oExcel := ComObjActive("Excel.Application"). More info here.

How to access active Workbook?

Code: Select all

try
oWorkbook :=	Excel_Get().ActiveWorkbook ; try to access active Workbook object
catch
return ; case when Excel doesn't exist, or it exists but there is no active workbook. Just Return or Exit or ExitApp.

; if there is active workbook, code continues execution...
oWorkbook.ActiveSheet.Range("B2").Value :=	"B2" ; set value of B2 cell in active sheet to "B2"
How to access Excel object from Workbook object?

Code: Select all

oExcel :=	oWorkbook.Application ; returns Excel application object that owns Workbook object
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 10:18

May need to edit content, I believe the While-loop can now be done as a For-loop

COM Object: PowerPoint.Application
Purpose: Create powerpoint presentations
System Requirements:Microsoft Office Powerpoint application, OS>Win2000
Documentation Link:MSDN article,WMI article
Other Links:Application Object
Basic Code Example:

Code: Select all

objPPT :=	ComObjCreate("PowerPoint.Application")
objPPT.Visible :=	True
objPresentation :=	objPPT.Presentations.Add
objPresentation.ApplyTemplate("C:\Program Files\Microsoft Office\Templates\Presentation Designs\Globe.pot")

strComputer :=	"."
objWMIService :=	ComObjGet("winmgmts:\\" . strComputer . "\root\cimv2")
colProcesses :=	objWMIService.ExecQuery("Select * From Win32_Process")._NewEnum

While colProcesses[objProcess]
{
	objSlide :=	objPresentation.Slides.Add(1,2)
	objShapes :=	objSlide.Shapes

	objTitle :=	objShapes.Item("Rectangle 2")
	objTitle.TextFrame.TextRange.Text :=	objProcess.Name

	strText :=	"Working set size: " . objProcess.WorkingSetSize . "`r`n"
	strText .=	"Priority: " . objProcess.Priority . "`r`n"
	strText .=	"Thread count: " . objProcess.ThreadCount . "`r`n"

	objTitle :=	objShapes.Item("Rectangle 3")
	objTitle.TextFrame.TextRange.Text :=	strText
}

objPresentation.SaveAs(A_ScriptDir . "\Process.ppt")
MsgBox %	objPresentation.Slides.Count . " slides saved to " . A_ScriptDir . "\Process.ppt"
objPresentation.Close
objPPT.Quit
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 10:24

COM Object: XStandard.Zip
Purpose: Zip & Unzip with many features
System Requirements: 32-bit OS, XZip.dll
Documentation Link: http://www.xstandard.com/en/documentation/xzip/
Other Links:
Basic Code Example:

How to archive (or zip) multiple files

Code: Select all

objZip :=	ComObjCreate("XStandard.Zip")
objZip.Pack("C:\Temp\golf.jpg", "C:\Temp\images.zip")
objZip.Pack("C:\Temp\racing.gif", "C:\Temp\images.zip")
How to archive (or zip) multiple files with different compression levels

Code: Select all

objZip :=	ComObjCreate("XStandard.Zip")
objZip.Pack("C:\Temp\reports.doc", "C:\Temp\archive.zip","" ,"" , 9)
objZip.Pack("C:\Temp\boat.jpg", "C:\Temp\archive.zip","" ,"" , 1)
How to archive (or zip) multiple files with default path

Code: Select all

objZip :=	ComObjCreate("XStandard.Zip")
objZip.Pack("C:\Temp\reports.doc", "C:\Temp\archive.zip", True)
objZip.Pack("C:\Temp\boat.jpg", "C:\Temp\archive.zip", True)
How to archive (or zip) multiple files with a custom pat

Code: Select all

objZip :=	ComObjCreate("XStandard.Zip")
objZip.Pack("C:\Temp\reports.doc", "C:\Temp\archive.zip", True, "files/word")
objZip.Pack("C:\Temp\boat.jpg", "C:\Temp\archive.zip", True, "files/images")
How to archive (or zip) multiple files using wildcards

Code: Select all

objZip :=	ComObjCreate("XStandard.Zip")
objZip.Pack("C:\Temp\*.jpg", "C:\Temp\images.zip")
How to unzip files

Code: Select all

objZip :=	ComObjCreate("XStandard.Zip")
objZip.UnPack("C:\Temp\images.zip", "C:\Temp\")
How to unzip files using wildcards

Code: Select all

objZip :=	ComObjCreate("XStandard.Zip")
objZip.UnPack("C:\Temp\images.zip", "C:\Temp\", "*.jpg")
How to get a listing of files and folder in an archive

Code: Select all

objZip :=	ComObjCreate("XStandard.Zip")
objContents :=	objZip.Contents(A_ScriptDir . "\test.zip")._NewEnum
For objItem in objZip.Contents(A_ScriptDir . "\test.zip")
	Msgbox %	objItem.Path . objItem.Name . "`n"
How to remove a file from an archive

Code: Select all

objZip :=	ComObjCreate("XStandard.Zip")
objZip.Delete("headshots/smith.jpg", "C:\Temp\images.zip")
How to move a file in an archive

Code: Select all

objZip :=	ComObjCreate("XStandard.Zip")
objZip.Move("headshots/jones.jpg", "staff/jones.jpg", "C:\Temp\images.zip")
How to rename a file in an archive

Code: Select all

objZip :=	ComObjCreate("XStandard.Zip")
objZip.Move("headshots/jones.jpg", "headshots/randy-jones.jpg", "C:\Temp\images.zip")
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 10:26

COM Object: Shell.Application
Purpose: Retrieves file properties.
System Requirements: General
Documentation Link: GetDetailsOf, ParseName
Other Links: Retrieving Extended File Properties
Basic Code Example - this example demonstrates how to retrieve the properties of a specified file :

Code: Select all

filepath :=	"C:\Windows\System32\notepad.exe"	;set the target full file path

SplitPath, filepath , FileName, DirPath,

objShell :=	ComObjCreate("Shell.Application")
objFolder :=	objShell.NameSpace(DirPath)		;set the directry path
objFolderItem :=	objFolder.ParseName(FileName)	;set the file name

Loop 283	
	if	propertyitem :=	objFolder.GetDetailsOf(objFolderItem, A_Index)
		properties .=	A_Index . " " .  objFolder.GetDetailsOf(objFolder.Items, A_Index) . ":`t " . propertyitem . "`n"

msgbox %	properties
User avatar
sinkfaze
Posts: 411
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 10:31

The previous example is for extended properties. This is for general properties.

COM Object: winmgmts
Purpose: Retrieves file&folder properties.
System Requirements: General
Documentation Link: Enumerating Folders and Folder Properties, Enumerating Files and File Properties
Basic Code Example - this example demonstrates how to retrieve the properties of a specified file and folder:

Code: Select all

filepath :=	"C:\Windows\System32\notepad.exe"	;set the target full file path
StringReplace, filepath, filepath, \, \\, All	;double backslashes
objWMIService :=	ComObjGet("winmgmts:{impersonationLevel=impersonate}!\\" . A_ComputerName . "\root\cimv2") 
WQLQuery = SELECT * FROM CIM_Datafile WHERE Name = '%filepath%'		;CIM_Datafile

For objFile in objWMIService.ExecQuery(WQLQuery) {
	FileProperties :=	"Access mask:`t`t" . objFile.AccessMask . "`n"
	 . "Archive:`t`t`t" . objFile.Archive . "`n"
	 . "Compressed:`t`t" . objFile.Compressed . "`n"
	 . "Compression method:`t`t" . objFile.CompressionMethod . "`n"
	 . "Creation date:`t`t" . objFile.CreationDate . "`n"
	 . "Computer system name:`t" . objFile.CSName . "`n"
	 . "Drive:`t`t`t" . objFile.Drive . "`n"
	 . "8.3 file name:`t`t" . objFile.EightDotThreeFileName . "`n"
	 . "Encrypted:`t`t" . objFile.Encrypted . "`n"
	 . "Encryption method:`t" . objFile.EncryptionMethod . "`n"
	 . "Extension:`t`t`t" . objFile.Extension . "`n"
	 . "File Name:`t`t" . objFile.FileName . "`n"
	 . "File Size:`t`t`t" . objFile.FileSize . "`n"
	 . "File Type:`t`t`t" . objFile.FileType . "`n"
	 . "File system name:`t`t" . objFile.FSName . "`n"
	 . "Hidden:`t`t`t" . objFile.Hidden . "`n"
	 . "Last accessed:`t`t" . objFile.LastAccessed . "`n"
	 . "Last modified:`t`t" . objFile.LastModified . "`n"
	 . "Manufacturer:`t`t" . objFile.Manufacturer . "`n"
	 . "Name:`t`t`t" . objFile.Name . "`n"
	 . "Path:`t`t`t" . objFile.Path . "`n"
	 . "Readable:`t`t`t" . objFile.Readable . "`n"	
	 . "System:`t`t`t" . objFile.System . "`n"
	 . "Version:`t`t`t" . objFile.Version . "`n"
	 . "Writeable:`t`t`t" . objFile.Writeable 
}
msgbox %	FileProperties

Code: Select all

folderpath :=	"C:\Windows\System32"	;set the target full foler path
folderpath :=	RTrim(folderpath,"\") ;remove a trailing backslash, if present 
StringReplace, folderpath, folderpath, \, \\, All	;double backslashes
objWMIService :=	ComObjGet("winmgmts:{impersonationLevel=impersonate}!\\" . A_ComputerName . "\root\cimv2") 
WQLQuery = SELECT * FROM Win32_Directory WHERE Name = '%folderpath%'	;Win32_Directory

For objFolder in objWMIService.ExecQuery(WQLQuery) {
	FolderProperties :=	"Archive:`t`t`t" . objFolder.Archive . "`n"
	 . "Caption:`t`t`t" . objFolder.Caption . "`n"
	 . "Compressed:`t`t" . objFolder.Compressed . "`n"
	 . "Compression method:`t" . objFolder.CompressionMethod . "`n"
	 . "Creation date:`t`t" . objFolder.CreationDate . "`n"
	 . "Encrypted:`t`t" . objFolder.Encrypted . "`n"
	 . "Encryption method:`t`t" . objFolder.EncryptionMethod . "`n"
	 . "Hidden:`t`t`t" . objFolder.Hidden . "`n"
	 . "In use count:`t`t" . objFolder.InUseCount . "`n"
	 . "Last accessed:`t`t" . objFolder.LastAccessed . "`n"
	 . "Last modified:`t`t" . objFolder.LastModified . "`n"
	 . "Name:`t`t`t" . objFolder.Name . "`n"
	 . "Path:`t`t`t" . objFolder.Path . "`n"
	 . "Readable:`t`t`t" . objFolder.Readable . "`n"
	 . "System:`t`t`t" . objFolder.System . "`n"
	 . "Writeable:`t`t`t" . objFolder.Writeable
}
msgbox %	FolderProperties

Return to “Scripts and Functions”

Who is online

Users browsing this forum: arcticir, djseo, Google [Bot], hotkeyguy, robodesign, TheDewd and 25 guests