COM Object Reference

Post your working scripts, libraries and tools for AHK v1.1 and older
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 10:38

Another way to retrieve file/folder properties.

COM Object: Scripting.FileSystemObject
Purpose: Retrieves file & folder properties.
System Requirements: General
Documentation Link: FileSystemObject
DateLastAccessed Property, DateCreated Property, DateLastModified Property
Size Property
Name Property
Shortname Property
Type property
Attributes Property
Path Property
Shortpath Property

Basic Code Example - this example demonstrates how to retrieve the properties of a specified file and folder via FileSystemObject:

Code: Select all

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

objFSO :=	ComObjCreate("Scripting.FileSystemObject")
ComObjError(false)   ;disable COM error messages for some non available properties
objFile :=	objFSO.GetFile(filepath)
objFolder :=	objFSO.GetFolder(folderpath)

FileProperties :=	"Date Created:`t`t" . objFile.DateCreated . "`n"  
	 . "Last Accessed:`t`t" . objFile.DateLastAccessed . "`n"
	 . "Last Modified:`t`t" . objFile.DateLastModified . "`n"
	 . "File Size(bytes):`t`t" . objFile.Size . "`n"  
	 . "File Name:`t`t" . objFile.Name . "`n" 
	 . "File Short Name:`t`t" . objFile.ShortName . "`n" 
	 . "File Type:`t`t`t" . objFile.Type . "`n"  
	;Attributes 0: Normal 1:ReadOnly 2:Hidden 4:System 8:Volume 16:Directroy 32:Archive 1024:Alias 2048:Compressed
	 . "Attributes:`t`t`t" . objFile.attributes . "`n"  
	 . "File Path:`t`t`t" . objFile.Path  . "`n"   
	 . "File Short Path:`t`t" . objFile.ShortPath  . "`n"   
	
FolderProperties :=	"Date Created:`t`t" . objFolder.DateCreated . "`n" 
	 . "Last Accessed:`t`t" . objFolder.DateLastAccessed . "`n"
	 . "Last Modified:`t`t" . objFolder.DateLastModified . "`n"
	 . "Size(bytes):`t`t" . objFolder.Size . "`n"
	 . "Folder Name:`t`t" . objFolder.Name . "`n"
	 . "Folder Short Name:`t`t" . objFolder.ShortName . "`n" 
	 . "Folder Type:`t`t" . objFolder.Type . "`n"  
	 . "Attributes:`t`t`t" . objFolder.attributes . "`n" 
	 . "Folder Path:`t`t" . objFolder.Path  . "`n"  
	 . "Folder Short Path:`t`t" . objFolder.ShortPath  
	
ComObjError(true)      

msgbox %	FileProperties
msgbox %	FolderProperties
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 18:51

COM Object: winmgmts
Purpose: Manipulating Services
System Requirements: General
Documentation Link: Win32_Service Class
WMI Scripting Primer: Part 3
Services
Other Links: Scripts to manage Services
Basic Code Example - retrieves service information and demonstrates starting and stopping a service:

Code: Select all

objWMIService :=	ComObjGet("winmgmts:{impersonationLevel=impersonate}!\\" . A_ComputerName . "\root\cimv2") 

;Determining the services which can be stopped
WQLQuery = SELECT * FROM Win32_Service WHERE AcceptStop = True		;"AcceptStop = True"
count :=	0
For objService in objWMIService.ExecQuery(WQLQuery)
	StoppableServices .=	objService.DisplayName . "`n", count++
MsgBox,, Services which can be stopped: %count%, %StoppableServices%

;Determining the services wich can be paused
WQLQuery = SELECT * FROM Win32_Service WHERE AcceptPause = True		;AcceptPause = True
count :=	0
For objService in objWMIService.ExecQuery(WQLQuery)
	PausableServices .=	objService.DisplayName . "`n", count++
MsgBox,, Services which can be paused: %count%, %PausableServices%

;Retrieves a complete list of services and their associated properties.
WQLQuery = Select * from Win32_Service
For objService in objWMIService.ExecQuery(WQLQuery) {
	ServicePropertyList .=	objService.DisplayName . "`n"
	 . "`tSystemName:`t" . objService.SystemName . "`n"
	 . "`tName:`t" . objService.Name . "`n"
	 . "`tServiceType:`t" . objService.ServiceType . "`n"
	 . "`tState:`t" . objService.State . "`n"
	 . "`tExitCode:`t" . objService.ExitCode . "`n"
	 . "`tProcessID:`t" . objService.ProcessID . "`n" 
	 . "`tAcceptPause:`t" . objService.AcceptPause . "`n" 
	 . "`tAcceptStop:`t" . objService.AcceptStop . "`n" 
	 . "`tCaption:`t" . objService.Caption . "`n" 
	 . "`tDescription:`t" . objService.Description . "`n" 
	 . "`tDesktopInteract:`t" . objService.DesktopInteract . "`n" 
	 . "`tDisplayName:`t" . objService.DisplayName . "`n" 
	 . "`tErrorControl:`t" . objService.ErrorControl . "`n" 
	 . "`tPathName:`t" . objService.PathName . "`n" 
	 . "`tStarted:`t" . objService.Started . "`n" 
	 . "`tStartMode:`t" . objService.StartMode . "`n" 
	 . "`tStartName:`t" . objService.StartName . "`n" 	
}
logfile = %A_ScriptDir%\ServicePropertyList.txt
FileDelete, %logfile%
FileAppend, %ServicePropertyList%, %logfile%
Run, Notepad "%logfile%"

Code: Select all

;Run As Admin
if	not A_IsAdmin {
	If	A_IsCompiled
		DllCall("shell32\ShellExecute" . (A_IsUnicode ? "" :"A"), (A_PtrSize=8 ? ptr : uint), 0, str, "RunAs", str, A_ScriptFullPath, str, params , str, A_WorkingDir, int, 1)
	Else	DllCall("shell32\ShellExecute" . (A_IsUnicode ? "" :"A"), (A_PtrSize=8 ? ptr : uint), 0, str, "RunAs", str, A_AhkPath, str, """" . A_ScriptFullPath . """" . A_Space . params, str, A_WorkingDir, int, 1)
	ExitApp
}

objWMIService :=	ComObjGet("winmgmts:{impersonationLevel=impersonate}!\\" . A_ComputerName . "\root\cimv2") 

;Determining which services are currently stopped and the start mode is 'Manual'
WQLQuery = SELECT DisplayName FROM Win32_Service Where State='Stopped' AND StartMode='Manual'
count :=	0
For objService in objWMIService.ExecQuery(WQLQuery)
	StoppedServices .=	objService.DisplayName . "`n", count++
MsgBox,, Services Currently Stopped and 'Manual': %count%, %StoppedServices%

;Start the First Service in the List of the Stopped Services of the 'Manual' mode
For objService in objWMIService.ExecQuery(WQLQuery) {
	DemoRunService :=	objService.DisplayName
	if	errReturnCode :=	objService.StartService()
		MsgBox, 48,, Error Code: %errReturnCode%`nCould Not Start the Service, %DemoRunService%
	else {
		Msgbox %DemoRunService%	is Started. After OK is Pressed, It Will be Stopped.
		if	errReturnCode :=	objService.StopService()
			MsgBox, 48,, Error Code: %errReturnCode%`nCould Not Stop the Service, %DemoRunService%
		else	Msgbox Successfully Stopped the Service : %DemoRunService%
	}
	Break	;just one service to start and stop for demo
}
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 18:56

COM Object: WScript.Shell
Purpose: Various Administration Tasks
System Requirements: General, WSH vertion 5.6 for the Exc() method
Documentation Link WshShell Object
Other Links: WSH Primer
Basic Code Example:

Code: Select all

;Retrieve console's outputs
;http://msdn.microsoft.com/en-us/library/cbxxzwb5(v=VS.85).aspx
;http://technet.microsoft.com/en-us/library/ee156605.aspx
objShell :=	ComObjCreate("WScript.Shell")
objExec :=	objShell.Exec("ipconfig.exe")
While	!objExec.Status	;wait until ipconfig.exe starts
	Sleep 100
strLine :=	objExec.StdOut.ReadAll()	;read the output at once
msgbox %	strLine   

objExec :=	objShell.Exec("cmd /c ping -n 3 -w 1000 www.google.com")
While	!objExec.StdOut.AtEndOfStream ;read the output line by line
	if	InStr(objExec.StdOut.ReadLine(), "Reply") {
		Msgbox Reply received.
		Break
	}

;Retrieve Special Folder paths
;http://technet.microsoft.com/en-us/library/ee156616.aspx
Msgbox %	"Desktop:`n`t" . objShell.SpecialFolders("Desktop") . "`n"
	 . "Favorites:`n`t" . objShell.SpecialFolders("Favorites") . "`n"
	 . "MyDocuments:`n`t" . objShell.SpecialFolders("MyDocuments") . "`n"
	 . "SendTo:`n`t" . objShell.SpecialFolders("SendTo") . "`n"
	 . "StartMenu:`n`t" . objShell.SpecialFolders("StartMenu") . "`n"
	 . "Startup:`n`t" . objShell.SpecialFolders("Startup")
	
;Add logs to Application Event Log 	
;http://technet.microsoft.com/en-us/library/ee156617.aspx
objShell.LogEvent(0, "Test Writing: Success")
objShell.LogEvent(1, "Test Writing: Error")
objShell.LogEvent(2, "Test Writing: Warning")
objShell.LogEvent(4, "Test Writing: Information")
objShell.LogEvent(8, "Test Writing: Audit Sucess")
objShell.LogEvent(16, "Test Writing: Audit Failure")	

;Hello World Script with MessageBox and Notepad
objExec :=	objShell.Exec("notepad.exe")			;Run, notepad,,, PID
While	!objShell.AppActivate(objExec.ProcessID)	;WinWaitActive, ahk_pid %PID%
	sleep 100
objShell.SendKeys("Hello World!{Enter}") ;Send, Hell World{Enter}
iBtn :=	objShell.Popup("Do you cancel?", 5, "Continue?", 33)	;Msgbox,33, Continue?, Do you cancel?, 5
if	iBtn = 1         ;OK is pressed
	objShell.Popup("Done", 5, "You pressed OK", 64)
else if	iBtn = 2    ;Cancel is pressed
	objShell.Popup("Canceled", 5, "You pressed Cancel", 64)
else	;Timeout or other reasons
	objShell.Popup("Forced Execution", 5, "None pressed", 64)
objExec.Terminate()								;Process, Close, %PID%
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 18:59

COM Object: WScript.Shell
Purpose: Exchange variables between scripts
System Requirements: General
Documentation Link: WshEnvironment Object
Other Links: Environment Variables
Basic Code Example - demonstrates how to set a volatile environment variable and read it from another script:Save this code as Sender.ahk

Code: Select all

objShell :=	ComObjCreate("WScript.Shell")
objEnv :=	objShell.Environment("Volatile")
loop {
	random, env, 0, 100
	;Here the variable is named "Test". Change the name as you need.
	;But the other script to read the value needs the corresponding variable name.
	;This variable and its value will be lost after logout/restart/shutdown of your computer.
	objEnv.Item("Test") :=	env
	sleep 100
}
Return
Save this code as Receiver.ahk

Code: Select all

objShell :=	ComObjCreate("WScript.Shell")
objEnv :=	objShell.Environment("Volatile")
loop {
	tooltip %	objEnv.Item("Test")
	sleep 100
}
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 19:09

COM Object: Excel.Application
Purpose: Work with SafeArray and Range in Excel
System Requirements: General
Basic Code Example
Hotkeys: F1 - set values to Range("A1:B3") via SafeArray, F2 - get values from Range("A1:B3") via SafeArray

Code: Select all

#IfWinActive, ahk_class XLMAIN
;===================================================================================
F1::	; set values to Range("A1:B3") via SafeArray
SafeArray :=	ComObjArray(12, 3, 2)	; create a safe array. "12" means VT_VARIANT, "3" means 3 rows (1. dimension), "2" means 2 columns (2. dimension)

; Note: when building a SafeArray to assign to an Excel Range Value, it will be 0-based
Loop, 3	; 3 rows
{
	RowNum :=	A_Index-1
	Loop, 2	;  2 columns
	{
		ColNum :=	A_Index-1
		SafeArray[RowNum, ColNum] :=	"Row" RowNum +1  " Col" ColNum + 1
	}
}

oExcel :=	ComObjActive("Excel.Application")
oExcel.Range("A1:B3").value :=	SafeArray 	; set safe array to range object
return


;===================================================================================
F2::	; get values from Range("A1:B3") via SafeArray
oExcel :=	ComObjActive("Excel.Application")

SafeArray :=	oExcel.Range("A1:B3").value	; get safe array

;MsgBox %	SafeArray.MaxIndex(1)   ; get total rows (1. dimension)
;MsgBox %	SafeArray.MaxIndex(2)   ; get total columns (2. dimension)

; Note: when extracting the SafeArray, it will be 1-based
Loop %	SafeArray.MaxIndex(1) ; loop through every row
{
	CurRowNum :=	A_Index
	Loop %	SafeArray.MaxIndex(2)  ; loop through every column
		MsgBox,,, %	SafeArray[CurRowNum, A_Index], 1    ; get cell's value
}
return

Code: Select all

DemoString =
(
Jack%A_Tab%Gates%A_Tab%Driver%A_Tab%
Mark%A_Tab%Weber%A_Tab%Student%A_Tab%His father is a driver.
Jim%A_Tab%Tucker%A_Tab%Driver%A_Tab%
Jill%A_Tab%Lochte%A_Tab%Artist%A_Tab%Jack's sister.
)


#IfWinActive, ahk_class XLMAIN
F1::	; set 2 dimensional object to Range("A1:D4") via SafeArray
oExcel :=	ComObjActive("Excel.Application")
SafeArray(oExcel.Range("A1:D4"), String2Table(DemoString))
return

F2::	; get 2 dimensional object from Selection or any other range object via SafeArray, and convert it to string
oExcel :=	ComObjActive("Excel.Application")
MsgBox %	Table2String(SafeArray(oExcel.Selection))
return



;===Functions===========================================================================
SafeArray(oRange, oTable="") {	; Sets or gets SafeArray. By Learning one.
	/*
		Parameters:
		oRange		MS Excel range object
		oTable		2 dimensional array object
	
		Operation:
		if oTable is empty		function gets SafeArray from specified oRange and returns it as oTable
		else					function converts oTable to SafeArray, and sets it to specified oRange
	*/
	
	if	(oTable = "")	; get SafeArray
	{
		oTable :=	Object()
		SafeArray :=	oRange.value
		if	(SafeArray.MaxIndex(1) = "")	; just one cell range
			return	SafeArray	; return as var not object
	
		Loop %	SafeArray.MaxIndex(1) ; loop through every row
		{
			RowNum :=	A_Index
			%RowNum% :=	Object()
			Loop %	SafeArray.MaxIndex(2)  ; loop through every column
				%RowNum%.Insert(SafeArray[RowNum, A_Index])
			oTable.Insert(%RowNum%)
		}
		return	oTable
	}
	else	; set SafeArray
	{
		if	!IsObject(oTable)
		{
			oRange.value :=	oTable
			return
		}
		For k,v in oTable
		{
			Dimension1 ++	; rows
			CurMaxCol :=	oTable[k].MaxIndex()
			if	(CurMaxCol > Dimension2)
				Dimension2 :=	CurMaxCol
		}
		SafeArray :=	ComObjArray(12, Dimension1, Dimension2)
		Loop, %	Dimension1	; rows
		{
			RowNum :=	A_Index-1
			Loop, %	Dimension2	;  columns
			{
				ColNum :=	A_Index-1
				SafeArray[RowNum, ColNum] :=	oTable[RowNum+1][ColNum+1]
			}
		}
		oRange.value :=	SafeArray 
	}
}

String2Table(String, ColumnsDelimiter="`t", RowsDelimiter= "`n") {	; converts string to table object (2 dimensional). By Learning one.
	oTable :=	Object()
	Loop, parse, String, %RowsDelimiter%
	{
		CurRow :=	A_LoopField, RowNum :=	A_index
		%RowNum% :=	Object()
		Loop, parse, CurRow, %ColumnsDelimiter%
			%RowNum%.Insert(A_LoopField)
		oTable.Insert(%RowNum%)
	}
	return	oTable
}

Table2String(oTable, ColumnsDelimiter="`t", RowsDelimiter= "`n") {	; converts table object (2 dimensional) to string. By Learning one.
	if	!IsObject(oTable)	; var passed as obj
		return	oTable
	For k,v in oTable
	{
		For k2,v2 in oTable[k]
			RowString .=	v2 ColumnsDelimiter
			RowString :=	RTrim(RowString, ColumnsDelimiter)
			TableString .=	RowString RowsDelimiter
			RowString =
	}
	return	RTrim(TableString, RowsDelimiter)
}
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 19:11

COM Object: Shell.Application [Folder Object]
Purpose: Access/Manipulate Folders
System Requirements: General
Documentation Link: Shell Object, Folder Object
Code Example: Rename Folders/Files without using FileCopy(Dir)

Code: Select all

;// Create an example directory
dir :=	A_Desktop "\Example_Dir"
FileCreateDir, %dir%\Temp
Loop 9
	FileAppend, , %dir%\_%A_Index%.txt
Run %dir%
MsgBox, 262144, , Press OK to add Prefix to files...

;// Loop through the folder items. Add a Prefix to the files.
objFolder :=	ComObjCreate("Shell.Application").NameSpace(dir)
for item in objFolder.items
	if	Not item.isFolder
		item.name :=	"File" item.name

;// Delete example directory
MsgBox Deleting Directory...
FileRemoveDir, %dir%, 1
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 19:17

COM Object: Shell.Explorer [Embedded Browser]
Purpose: Embed a Trident Browser (IE) in a Gui
System Requirements: General
Documentation Link: Shell.Explorer, iWebBrowser2
Basic Code Example: Embed a browser navigate to a web site and wait for it to loadEvery one asks why ctrl+key comboes and enter do not work in theier implementation of this. Please see how this is solved in this example

Code: Select all

/*
	written by tank updated by Jethrow
	
	AHK_L version 1.0.90.00 ansii 32 bit or higher
	
	Date : 10/18/2011
*/
main:
{
	Gosub,init
	url:="http://www.google.com"
	WB.Navigate(url)
	loop
		If	!WB.busy
			break
	return
}

init:
{
	;// housekeeping routines
	;// set the tear down procedure
	OnExit,terminate
	
	;// Create a gui
	Gui, +LastFound +Resize +OwnDialogs
	
	;// create an instance of Internet Explorer_Server
	;// store the iwebbrowser2 interface pointer as *WB* & the hwnd as *ATLWinHWND*
	Gui, Add, ActiveX, w510 h600 x0 y0 vWB hwndATLWinHWND, Shell.Explorer
	
	;// disable annoying script errors from the page
	WB.silent :=	true
	
	;// necesary to accept enter and accelorator keys
	;http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.ole.interop.ioleinplaceactiveobject(VS.80).aspx
	IOleInPlaceActiveObject_Interface:="{00000117-0000-0000-C000-000000000046}"
	
	;// necesary to accept enter and accelorator keys
	;// get the in place interface pointer
	pipa :=	ComObjQuery(WB, IOleInPlaceActiveObject_Interface)
	
	;// necesary to accept enter and accelorator keys
	;// capture key messages
	OnMessage(WM_KEYDOWN:=0x0100, "WM_KEYDOWN")
	OnMessage(WM_KEYUP:=0x0101, "WM_KEYDOWN")
	
	;//Display the GUI
	gui,show, w510 h600 ,Gui Browser
	
	;// return and allow the program
	return
}

;// capture the gui resize event
GuiSize:
{
	;// if there is a resize event lets resize the browser
	WinMove, %	"ahk_id " . ATLWinHWND, , 0,0, A_GuiWidth, A_GuiHeight
	return
}

GuiClose:
terminate:
{
	;// housekeeping
	;// destroy the gui
	Gui, Destroy
	;// release the in place interface pointer
	ObjRelease(pipa)
	ExitApp
}



WM_KEYDOWN(wParam, lParam, nMsg, hWnd)  ;// modeled after code written by lexikos
{
	global	wb, pipa
	static	fields :=	"hWnd,nMsg,wParam,lParam,A_EventInfo,A_GuiX,A_GuiY"
	WinGetClass, ClassName, ahk_id %hWnd%
	if	(ClassName = "Internet Explorer_Server")
	{
		;// Build MSG Structure
		VarSetCapacity(Msg, 48)
		Loop Parse, fields, `,
			NumPut(%A_LoopField%, Msg, (A_Index-1)*A_PtrSize)
		;// Call Translate Accelerator Method
		TranslateAccelerator :=	NumGet(NumGet(1*pipa)+5*A_PtrSize)
		Loop 2 ;// only necessary for Shell.Explorer Object
			r :=	DllCall(TranslateAccelerator, "Ptr",pipa, "Ptr",&Msg)
		until	wParam != 9 || wb.document.activeElement != ""
	
		if	r = 0 ;// S_OK: the message was translated to an accelerator.
			return	0
	}
}
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 19:21

COM Object: WMPlayer.OCX
Purpose: Play Media Files; Embed WMP control in GUI
System Requirements: Windows Media Player 9 Series or later
Documentation Link: Player Object
Code Example:

Code: Select all

FileSelectFile, file, 2, %A_MyDocuments%, Select WMP Compatable File:
if	Errorlevel
	ExitApp

wmp :=	ComObjCreate("WMPlayer.OCX")
ComObjConnect(wmp, "wmp_") ;// show player status in TrayTip
wmp.url :=	file ;// play file
	
Message("Pause")
wmp.controls.pause

Message("Unpause")
wmp.controls.play

Message("Speed Up")
wmp.settings.rate :=	1.5

Message("Return to Normal Speed")
wmp.settings.rate :=	1 

Message("Load File in WMP App & Close Script")
wmp.close
wmp.openPlayer(file)

wmp :=	""  ;// release/disconnect object

wmp_StatusChange(wmp) {
	TrayTip, , %	"Status: " wmp.status
	 .  "`nDuration: " wmp.currentMedia.durationString
}

Message(str) {
	ToolTip, Press CTRL to %str%
	KeyWait, CTRL, D
	KeyWait, CTRL 
	ToolTip
}
Embed player in a GUI:

Code: Select all

FileSelectFile, file, 2, %A_MyDocuments%, Select WMP Compatable File:
if	Errorlevel
	ExitApp

Gui, +LastFound +Resize
Gui, Add, ActiveX, x0 y0 w500 h300 vWMP, WMPLayer.OCX
WMP.Url :=	file
Gui, Show, w500 h300 Center, Player GUI
SetTimer, Position, 1000
return

GuiClose:
	ExitApp

GuiSize:
	GuiControl, Move, WMP, w%A_GuiWidth%	h%A_GuiHeight%
	return
	
Position:
	Gui, Show, NA, %	WMP.CurrentMedia.name " - " Format(WMP.Controls.currentPosition) " / " Format(WMP.CurrentMedia.duration)
	return

Format(m1) {
	static	units :=	"sec,min,hr"
	Loop Parse, units, csv
		RegExMatch(m1/60, "(.*)(\.\d*)", m), %A_LoopField% :=	Pad(Round(m2*60))
	return	(hr? hr ":":"") min ":" sec
}

Pad(p) {
	return	(p<10? "0":"") p
}
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 19:34

COM Object: Ahk.ComSurrogate.32/64
Purpose: Create COM objects of a specified bitness
System Requirements: ComDispatch.ahk (with the included ComRemote.ahk library)
Description:This is a simple COM script that proxies the creation of 32-bit only objects on 64-bit scripts and vice versa.

Code: Select all

;
; File encoding:  UTF-8
; Author: fincs
;
; COM 32bit<->64bit object creation surrogate
;

#NoEnv
SendMode Input
SetWorkingDir, %A_ScriptDir%

#Persistent
;#NoTrayIcon
#SingleInstance Off
#Include ComRemote.ahk

; CLSID and APPID for this script: don't reuse, please!
if	A_PtrSize = 4
{
	CLSID_ThisScript :=	"{EB42F5B6-31A0-4B9D-8C6D-757FE4136B2C}"
	APPID_ThisScript :=	"Ahk.ComSurrogate.32"
}
else if	A_PtrSize = 8
{
	CLSID_ThisScript :=	"{CC2D93BB-3818-40E6-9405-804512FF23DC}"
	APPID_ThisScript :=	"Ahk.ComSurrogate.64"
}
else
{
	MsgBox, 16,, What kind of weird AHK build are you running?!
	ExitApp
}

ComObjError(false)
test :=	ComObjActive(APPID_ThisScript)
if	IsObject(test)
	ExitApp ; already running
ComObjError(true)

; Register our CLSID and APPID
OnExit, IDCleanup
RegisterIDs(CLSID_ThisScript, APPID_ThisScript)

; Create a dispatch object for exposing
myObj :=	ComDispatch("", "ObjCreate=Wrap_ObjCreate, Close=Wrap_Close")
; Expose it
if	!(hRemote :=	ComRemote(myObj, CLSID_ThisScript))
{
	MsgBox, 16, %A_ScriptName%, Can't remote the object!
	ExitApp
}

; End of auto-run section
return

IDCleanup:
; Remove the CLSID and APPID from the registry
RevokeIDs(CLSID_ThisScript, APPID_ThisScript)
ExitApp

RegisterIDs(CLSID, APPID)
{
	RegWrite, REG_SZ, HKCU, Software\Classes\%APPID%,, %APPID%
	RegWrite, REG_SZ, HKCU, Software\Classes\%APPID%\CLSID,, %CLSID%
	RegWrite, REG_SZ, HKCU, Software\Classes\CLSID\%CLSID%,, %APPID%
}

RevokeIDs(CLSID, APPID)
{
	RegDelete, HKCU, Software\Classes\%APPID%
	RegDelete, HKCU, Software\Classes\CLSID\%CLSID%
}

Str2GUID(ByRef var, str)
{
	VarSetCapacity(var, 16)
	DllCall("ole32\CLSIDFromString", "wstr", str, "ptr", &var)
	return	&var
}

; --------------------------------------------

Wrap_ObjCreate(this, ProgIDorCLSID)
{
	return	ComObjCreate(ProgIDorCLSID)
}

Wrap_Close(this)
{
	Critical
	SetTimer, _Close, -0
}

_Close:
ExitApp
You need to have it running in the background using the AHK_L build of the appropriate bitness (running both AHK_L builds at the same time is supported), then you can use these functions to create objects:

Code: Select all

ComCreateObj32(ProgIDorCLSID)
{
	static	_sur :=	A_PtrSize = 8 ? ComObjActive("Ahk.ComSurrogate.32") : ""
	return	A_PtrSize = 8 ? _sur.ObjCreate(ProgIDorCLSID) : ComObjCreate(ProgIDorCLSID)
}

ComCreateObj64(ProgIDorCLSID)
{
	static	_sur :=	A_PtrSize = 4 ? ComObjActive("Ahk.ComSurrogate.64") : ""
	return	A_PtrSize = 4 ? _sur.ObjCreate(ProgIDorCLSID) : ComObjCreate(ProgIDorCLSID)
}
Example: ScriptControl on 64-bit AHK_L:

Code: Select all

oSC :=	ComCreateObj32("ScriptControl"), oSC.Language :=	"VBScript"
oSC.ExecuteStatement("MsgBox ""Hello World!""")
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 20:17

COM Object: WIA.CommonDialog/WIA.DeviceManager/WIA.ImageFile/WIA.ImageProcess/WIA.Rational/WIA.Vector
Purpose: acquire images on digital cameras, scanners, or Web cameras, and to rotate, scale, and annotate your image files.
System Requirements: require Windows XP Service Pack 1 (SP1) or later, and Windows Image Acquisition Automation Library v2.0 Tool
Documentation Link: http://msdn.microsoft.com/en-us/library/ms630827
Other Links:
Basic Code Example:

Display Detailed Image Information

The following example shows how to display detailed information about one of the sample pictures from Microsoft Windows XP.

Code: Select all

Img :=	ComObjCreate("WIA.ImageFile")

Img.LoadFile("C:\test.jpg")

s :=	"Width = " Img.Width "`n"
	 . "Height = " Img.Height "`n"
	 . "Depth = " Img.PixelDepth "`n"
	 . "HorizontalResolution = " Img.HorizontalResolution "`n"
	 . "VerticalResolution = " Img.VerticalResolution "`n"
	 . "FrameCount = " Img.FrameCount "`n"

If	Img.IsIndexedPixelFormat
{
	s :=	s "Pixel data contains palette indexes" "`n"
}

If	Img.IsAlphaPixelFormat
{
	s :=	s "Pixel data has alpha information" "`n"
}

If	Img.IsExtendedPixelFormat
{
	s :=	s "Pixel data has extended color information (16 bit/channel)" "`n"
}

If	Img.IsAnimated
{
	s :=	s "Image is animated" "`n"
}

If	Img.Properties.Exists("40091")
{
	v :=	Img.Properties("40091").Value
	s :=	s "Title = " v.String "`n"
}

If	Img.Properties.Exists("40092")
{
	v :=	Img.Properties("40092").Value
	s :=	s "Comment = " v.String "`n"
}

If	Img.Properties.Exists("40093")
{
	v :=	Img.Properties("40093").Value
	s :=	s "Author = " v.String "`n"
}

If	Img.Properties.Exists("40094")
{
	v :=	Img.Properties("40094").Value
	s :=	s "Keywords = " v.String "`n"
}

If	Img.Properties.Exists("40095")
{
	v :=	Img.Properties("40095").Value
	s :=	s "Subject = " v.String "`n"
}

MsgBox, %	s
return
Take a Picture

The following example shows how to signal a camera to take a picture if the device selected is a camera.

Code: Select all

objCommonDialog :=	ComObjCreate("WIA.CommonDialog")

dev :=	objCommonDialog.ShowSelectDevice

If	(dev.Type = CameraDeviceType)
	itm :=	dev.ExecuteCommand(wiaCommandTakePicture)
return
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 20:20

COM Object: Outlook.Application
Purpose: Create various new items in Outlook
System Requirements: Windows 2000 or higher
Documentation Link: Outlook 2003 Visual Basic Reference
Other Links: CreateItem Method, GetInspector Property, OlItemType constants
Basic Code Example: The entire process of creating a new Outlook item can be executed in a single line using one of the OlItemType constants shown in the below code (and in the above link) with the CreateItem method. This method is valuable if you have problems opening new items using the command line switches.

Code: Select all

/*
olAppointmentItem   1 
olContactItem   2 
olDistributionListItem   7 
olJournalItem   4 
olMailItem   0 
olNoteItem   5 
olPostItem   6 
olTaskItem   3 
*/

; will create a new mail item
ComObjActive("Outlook.Application").CreateItem[0].GetInspector.Display()

; will create a new note item
ComObjActive("Outlook.Application").CreateItem[5].GetInspector.Display()
And here's a sample ListBox GUI that will allow you to select and create a new instance of any of the applicable Outlook items:

Code: Select all

Gui, Add, Text, xm ym w325 Section, Select the Outlook item you wish to create:
Gui, Add, ListBox, r6 xs wp AltSubmit gItemSelection vitem,  Mail||Appointment|Contact|Task|Journal|Note|Post|Distribution List
Gui, Add, Button, xs+295 gCreateItem, OK
Gui, Show, AutoSize Center, Create New Outlook Item
return

ItemSelection:
CreateItem:
if	(A_ThisLabel="ItemSelection" && A_GuiEvent<>"DoubleClick")
	return
Gui, Submit
ComObjActive("Outlook.Application").CreateItem[item-1].GetInspector.Display()
Gui, Destroy
return

GuiCancel:
GuiClose:
Gui, Destroy
return
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 20:25

COM Object: CAPICOM Series
Purpose: digitally sign data, sign code, verify digital signatures, envelop data for privacy, hash data, encrypt/decrypt data and more.
System Requirements: 32-bit OS, for more details, please see MSDN
Documentation Link: CAPICOM Reference
Other Links:Platform SDK Redistributable: CAPICOM
Basic Code Example: First require to install capicom.dll from microsoft's site above.

Code: Select all

/*
************************************************************

	CAPIEncrypt.ahk

	This is a sample script to illustrate how to use the CAPICOMs EncryptedData 
	to encrypt/decrypt text file.

	Note: For simplicity, this script does not handle exception.

************************************************************
*/

ForReading :=	1
ForWriting :=	2

; CAPICOM's constants.                                             
CAPICOM_ENCRYPTION_ALGORITHM_RC2 :=	0
CAPICOM_ENCRYPTION_ALGORITHM_RC4 :=	1
CAPICOM_ENCRYPTION_ALGORITHM_DES :=	2
CAPICOM_ENCRYPTION_ALGORITHM_3DES :=	3
CAPICOM_ENCRYPTION_ALGORITHM_AES :=	4
	
CAPICOM_ENCRYPTION_KEY_LENGTH_MAXIMUM :=	0
CAPICOM_ENCRYPTION_KEY_LENGTH_40_BITS :=	1
CAPICOM_ENCRYPTION_KEY_LENGTH_56_BITS :=	2
CAPICOM_ENCRYPTION_KEY_LENGTH_128_BITS :=	3
CAPICOM_ENCRYPTION_KEY_LENGTH_192_BITS :=	4
CAPICOM_ENCRYPTION_KEY_LENGTH_256_BITS :=	5

strSF :=	"C:\test.txt"
strOF :=	"C:\Encrypted.txt"
Algorithm :=	CAPICOM_ENCRYPTION_ALGORITHM_AES
KeyLength :=	CAPICOM_ENCRYPTION_KEY_LENGTH_56_BITS
Password :=	"123456"

EncryptCommand(strSF, strOF, Algorithm, KeyLength, Password)
;~ DecryptCommand(strSF, strOF, Password)
return

; End Main


; EncryptCommand() - Encrypt content of text file ObjectFile.

EncryptCommand(SourceFile, ObjectFile, Algorithm, KeyLength, Password)
{
	Content :=	""
	Message :=	""
	EncryptedData :=	""
	
	; Create the EncryptedData object.
	EncryptedData :=	ComObjCreate("CAPICOM.EncryptedData")
	
	; algorithm, key size, and encryption password.
	EncryptedData.Algorithm.Name :=	Algorithm
	EncryptedData.Algorithm.KeyLength :=	KeyLength
	EncryptedData.SetSecret(Password)
	
	; Display main title.
	MsgBox, %	"Encrypting text file " . SourceFile . "."

	; Load content of text file to be encrypted.
	LoadFile(SourceFile, Content)
	
	; Now encrypt it.
	EncryptedData.Content :=	Content
	Message :=	EncryptedData.Encrypt
	
	; Finally, save encrypted message to strSF.
	SaveFile(ObjectFile, Message)
	MsgBox, %	"Successful - Encrypted message saved to " . ObjectFile . "."

	; Free resources.
	EncryptedData :=	""
	
}

; DecryptCommand() - Decrypt an encrypted file.

DecryptCommand(SourceFile, ObjectFile, Password)
{
	Message :=	""
	EncryptedData :=	""
	
	; Create the EncryptedData object.
	EncryptedData :=	ComObjCreate("CAPICOM.EncryptedData")
	
	; decryption password.
	EncryptedData.SetSecret(Password)
	
	; Display main title.
	MsgBox, %	"Decrypting encrypted text file " . SourceFile . "."
	
	; Load the encrypted message.
	LoadFile(SourceFile, Message)
	
	; Now decrypt it.
	EncryptedData.Decrypt(Message)
	
	; Finally, save decrypted content to strSF.
	SaveFile(ObjectFile, EncryptedData.Content)
	MsgBox, %	"Successful - Decrypted content saved to " . ObjectFile . "."
	
	; Free resources.
	EncryptedData :=	""

}

; LoadFile() - Read content of a text file.

LoadFile(FileName, ByRef Buffer)   
{
	global	ForReading
	objFSO :=	"", objTS :=	""
	
	objFSO :=	ComObjCreate("Scripting.FileSystemObject")

	If	Not objFSO.FileExists(FileName)
	{
		MsgBox, %	"Error: File " . FileName . " not found."
		ExitApp
	}
	
	objTS :=	objFSO.OpenTextFile(FileName, ForReading)  
	Buffer :=	objTS.ReadAll
}

; SaveFile() - Save string to file.

SaveFile(FileName, ByRef Buffer)
{
	global	ForWriting
	objFSO :=	"", objTS :=	""
	
	objFSO :=	ComObjCreate("Scripting.FileSystemObject")
	
	objTS :=	objFSO.OpenTextFile(FileName, ForWriting, True)
	objTS.Write(Buffer)
}
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 20:28

COM Object: Excel.Sheet
Purpose: Hold MS Excel Data - represents a MS Excel workbook
System Requirements: MS Excel
Documentation Link: WorkBook Object
Other Links: Excel Constants, Sort Method
Code Example:

Code: Select all

;// Excel Constants
xlMaximized :=	-4137
xlAsc :=	xlYes :=	1

;// Create WorkBook
XLBook :=	ComObjCreate("Excel.Sheet")
XLSht :=	XLBook.ActiveSheet

;// Maximize the WorkBook Control
XLBook.Windows(1).WindowState :=	xlMaximized
XLBook.Application.Visible :=	true

;// Fill in Data & Sort
for cell in XLSht.Range("A1:C10")
	if	(cell.row = 1)
		cell.value :=	"Header " A_Index
	else {
		Random, num, 0, 1
		cell.value :=	num
	}

;// Sort Data
MsgBox, Sorting by Column 1, then 2, then 3...
XLSht.Cells.Sort(   XLSht.Columns(1), xlAsc
	 , XLSht.Columns(2), ComObjMissing(), xlAsc
	 , XLSht.Columns(3), xlAsc
	 , xlYes )

;// Save WorkBook
MsgBox, 4, , The Workbook will close once the object is released - would you like to save it to the scirpt directory?
IfMsgBox, Yes
	XLBook.SaveAs(A_ScriptDir "\Excel.Sheet Example.xls")
Note - the Excel.Sheet object will open in the Active Excel Process (accessed by ComObjActive) - or will create a new Excel Process - and it will close when the pointer is released.
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 20:31

COM Object: Shell.Application [Folder & FolderItems object]
Purpose: Extract Files From/Unzip a Zip Directory
System Requirements: General
Documentation Link: Shell Object, Folder Object, FolderItems
Other Links: CopyHere Method
Code Example:

Code: Select all

ZipFolder :=	A_Desktop "\folder.zip"
NewDir :=	A_Desktop "\New Folder"

FileCreateDir, %NewDir%

shell :=	ComObjCreate("Shell.Application")
Folder :=	shell.NameSpace(ZipFolder)
NewFolder :=	shell.NameSpace(NewDir)

;// extract all
NewFolder.CopyHere(Folder.items, 4|16)
return

;// extract 1-by-1
for item in Folder.items
	NewFolder.CopyHere(item)
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 20:36

COM Object: Outlook.Application
Purpose: Personal Information Manager
System Requirements: MS Outlook (MS Office)
Documentation Link: Application Object
Other Links: Session Property, Folders Collection, MAPIFolder Object, MailItem Object
Basic Code Example: This example will access the Outlook Folders, and then each item in the Drafts Folder, assuming Outlook is already open.

Code: Select all

; Access the Session NameSpace
Session :=	ComObjActive("Outlook.Application").Session

; Access the Folders Collection
Folders :=	Session.Folders("Outlook Data File").Folders

; Loop through the MAPIFolders
Loop, %	Folders.Count
	t .=	Folders.item(A_Index).Name "`n"
MsgBox, %t%

; Loop through all the MailItems in the Drafts Folder
DraftItems :=	Folders.item("Drafts").Items
Loop, %	DraftItems.Count {
	Item :=	DraftItems.item(A_Index)
	MsgBox, %	"To:`t" Item.To
	 . "`nSubject:`t" Item.Subject
	 . "`nBody:`t" Item.Body
}
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 20:41

COM Object: ActiveX Data Objects (ADODB.Connection and others)
Purpose: Work with a variety of databases, such as CSV, Excel xls, Access mdb and so on.
System Requirements: General
Documentation Link: http://msdn.microsoft.com/en-us/library ... p/ms675532
Basic Code Example:

Code: Select all

sDatabaseName :=	"e:\TestDatabase.MDB"
adOpenStatic :=	3, adLockOptimistic :=	3, adUseClient :=	3

sConnectionString :=	"provider=Microsoft.Jet.OLEDB.4.0;Data Source=" . sDatabaseName
sCommandText :=	"SELECT ID,Name FROM MyTable"

; Create a database using ADOX
oCatalog :=	ComObjCreate("ADOX.Catalog")
oCatalog.Create(sConnectionString)
oTable :=	ComObjCreate("ADOX.Table")
oTable.Name :=	"MyTable"
oTable.Columns.Append("ID", 3)	; adInteger 3 Indicates a four-byte signed integer (DBTYPE_I4). 
oTable.Columns.Append("Name", 202, 50)	; adVarWChar 202 Indicates a null-terminated Unicode character string. 
oCatalog.Tables.Append(oTable)
oTable :=	""
oCatalog :=	""

; Connect to the database and query some data from it
oConnection :=	ComObjCreate("ADODB.Connection")
oConnection.Open(sConnectionString)
oRecordset :=	ComObjCreate("ADODB.Recordset")
oRecordset.CursorLocation :=	adUseClient
oRecordset.Open(sCommandText, oConnection, adOpenStatic, adLockOptimistic)

; Add new record
oRecordset.AddNew()
oRecordset.Fields["ID"].Value :=	1
oRecordset.Fields["Name"].Value :=	"AutoHotkey"
oRecordset.Update()

; Reading and display current record
If	!oRecordset.EOF
{
	MsgBox, %	"ID: " oRecordset.Fields["ID"].Value "`n"
	 . "Name: " oRecordset.Fields["Name"].Value
}

; Disconnect the connection
oRecordset.Close(), oConnection.Close()
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 20:46

COM Object: Outlook
Purpose: Demonstrate sending an email with attachments using Outlook
System Requirements: Windows 2000 or higher
Documentation Link: Outlook Object Model
Other Links: CreateItem Method, OlItemType constants, Attachments Collection, Recipients Collection
Basic Code Example: The following code copies the files from he A:\ drive to a backup folder, then emails them as attachments to the specified recipient.

Code: Select all

#NoEnv
#SingleInstance force
SetBatchLines -1
ListLines Off
SendMode Input
SetWorkingDir %A_ScriptDir%

; Autoexecute
global	DataDir :=	A_MyDocuments "\Reports\"
global	FileList :=	""

gosub	MakeSplashGUI

CopyFiles()
SendEmail()
ExitApp
return

CopyFiles()
{
	if	not FileExist("A:\*.*") {
		MsgBox 4144, No Files Found
		 , There are no files found on drive A:\`n`nOperation aborted!
		ExitApp
	}

	GuiControl Splash:, SplashText, Moving Files
	Gui Splash:Show

	; Move files from drive A:\ to backup
	Loop A:\*.*
	{
		FileMove %	A_LoopFileFullPath, %	DataDir, 1
		FileList .=	(FileList = "") ? "" : "`n"
		FileList .=	A_LoopFileName
	}
	Gui Splash:Cancel
}

SendEmail()
{
	if	(FileList = "")
	return

	; Create email message
	GuiControl Splash:, SplashText, Creating Email
	Gui Splash:Show

	omsg :=	ComObjCreate("Outlook.Application")
	NewMail :=	omsg.CreateItem(0) ; 0 = olMailItem
	NewMail.Subject :=	"Reports"
	NewMail.Body :=	""

	Recipient :=	NewMail.Recipients.Add("Somebody's Name")
	Recipient.Type :=	1 ; To: CC: = 2 BCC: = 3

	; Add attachments
	Loop Parse, FileList, `n, `r
	{
		NewMail.Body .=	A_LoopField "`n"
		NewMail.Attachments.Add(DataDir . A_LoopField)
	}

	; Send the email
	GuiControl Splash:, SplashText, Sending Email
	NewMail.Send()

	GuiControl Splash:, SplashText, Email Sent
	Sleep 2000
	Gui Splash:Cancel
}

MakeSplashGUI:
Gui Splash:+AlwaysOnTop -Caption +Border
Gui Splash:Font, bold
Gui Splash:Add, Text
 , r2 w250 vSplashText
 ,
return
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 20:50

COM Objects: msxml2.DOMDocument.6.0, msxml2.SAXXMLReader.6.0, msxml2.MXXMLWriter.6.0
Purpose: Format XML output
System Requirements: Windows XP SP3+, Microsoft Core XML Services (MSXML) 6.0
Documentation Link: XML DOM Reference
Other Links: Use MXXMLWriter
Basic Code Example:

Code: Select all

#NoEnv

;[========]
;[  Load  ]
;[========]
;-- Note: XML data from fincs.  The data has been edited to remove all formatting.
xmldata=
(ltrim join
	<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>
)

MsgBox Before:`n%xmldata%

;-- Create DOM object
xmlDoc:=ComObjCreate("msxml2.DOMDocument.6.0")
xmlDoc.async:=False

;-- Load XML data to DOM object
xmlDoc.loadXML(xmldata)
if	xmlDoc.parseError.errorCode
	{
		MsgBox
		 ,16
		 ,XML Load Error
		 ,%	"Unable to load XML data."
		  . "`nError: " . xmlDoc.parseError.errorCode
		  . "`nReason: " . xmlDoc.parseError.reason
		return
	}

;[==========]
;[  Format  ]
;[==========]
;-- Create SAXXMLReader and MXXMLWriter objects
xmlReader:=ComObjCreate("msxml2.SAXXMLReader.6.0")
xmlWriter:=ComObjCreate("msxml2.MXXMLWriter.6.0")

;-- Set properties on the XML writer.
;   Note: Some of the property assignments  have been commented out so that the
;   default values will be used.  Uncomment and set to another value if desired.

xmlWriter.byteOrderMark:=True
	;-- Determines whether to write the Byte Order Mark (BOM). The
	;   byteOrderMark property has no effect for BSTR or DOM output.

xmlWriter.disableOutputEscaping:=False
	;-- Matches the disable-output-escaping attribute of the <xsl:text> and
	;   <xsl:value-of> elements.  When set to True, special symbols such as
	;   "&" are passed through literally.

;;;;;xmlWriter.encoding:="UTF-8"
;;;;;    ;-- Sets and gets encoding for the output.  Observation: For some
;;;;;    ;   reason, encoding is not displayed in the processing instructions
;;;;;    ;   node if this property is set to "UTF-8".

xmlWriter.omitXMLDeclaration:=False
	;-- Forces the IMXWriter to skip the XML declaration.  Useful for
	;   creating document fragments.  Observation: For some reason (bug?),
	;   this property is assumed to be TRUE if the "output" property is a
	;   DOM object.

xmlWriter.indent:=True
	;-- Sets whether to indent output.  There is no real need for the
	;   xmlWriter without this feature

;;;;;xmlWriter.standAlone:=True
;;;;;    ;-- Sets the value of the standalone attribute in the XML declaration to
;;;;;    ;   "yes" or "no".

;;;;;xmlWriter.version:="1.0"
;;;;;    ;-- Specifies the version to include in XML declarations.
	
;;;;;xmlWriter.output:=""
;;;;;    ;-- Sets the destination and the type of output for IMXWriter.
;;;;;    ;   Observation: If set, this property should (must?) be set last.
	
;-- Set the XML writer to the SAX content handler
xmlReader.contentHandler :=xmlWriter
xmlReader.dtdHandler     :=xmlWriter
xmlReader.errorHandler   :=xmlWriter
xmlReader.putProperty("http://xml.org/sax/properties/lexical-handler",xmlWriter)
xmlReader.putProperty("http://xml.org/sax/properties/declaration-handler",xmlWriter)

;-- Trigger the xmlWriter format engine.  Show results.
xmlReader.parse(xmlDoc)
MsgBox %	"After:`n" . xmlWriter.output
	
;;;;;;[========]
;;;;;;[  Save  ]
;;;;;;[========]
;;;;;;-- Create output DOM object
;;;;;xmlOutputDoc:=ComObjCreate("Msxml2.DOMDocument.6.0")
;;;;;xmlOutputDoc.async:=False
;;;;;
;;;;;;-- Load and save
;;;;;xmlOutputDoc.loadXML(xmlWriter.output)
;;;;;xmlOutputDoc.save("FormattedXMLFile.xml")
;;;;;if xmlOutputDoc.parseError.errorCode
;;;;;    {
;;;;;    MsgBox
;;;;;        ,16
;;;;;        ,XML Save Error
;;;;;        ,%	"Unable to save XML data."
;;;;;        . "`nError: " . xmlOutputDoc.parseError.errorCode
;;;;;        . "`nReason: " . xmlOutputDoc.parseError.reason
;;;;;
;;;;;    return
;;;;;    }
;;;;;
;;;;;MsgBox Formatted XML saved to "FormattedXMLFile.xml".  %A_Space%
Although the flexibility of the XML writer is limited, the output is correctly parsed, formatted, and encoded.
User avatar
sinkfaze
Posts: 616
Joined: 01 Oct 2013, 08:01

Re: COM Object Reference

02 Oct 2013, 20:53

COM Object: VBSript.RegExp
Purpose: VBS Regular Expressions
System Requirements: General
Documentation Link: Regular Expression Object Properties and Methods, Microsoft Beefs Up VBScript with Regular Expressions
Basic Code Example: Global Regex match & replace

Code: Select all

haystack :=	"<A id='MyLink'>one<SPAN id='MyText'>two</SPAN>three</A>"

regex :=	ComObjCreate("VBScript.RegExp")
regex.Global :=	true
regex.IgnoreCase :=	true
regex.Pattern :=	"<.*?(id='\w+')?>"

match :=	regex.Execute(haystack)
t :=	"Haystack: " haystack "`nNeedle:`t " regex.Pattern "`n`n"

t .=	"`tPos (-1)`tLen`tVal`n`t------------------------------------------`n"
for item in match {
	_ :=	"[" A_Index-1 "]`t" 
	t .=	_ item.FirstIndex "`t" item.Length "`t" item.value "`n"
	s .=	_ item.SubMatches(0) "`n"
}
;// first character in the string is identified as 0
MsgBox,, %	match.count " Matches", %t%
MsgBox,, SubPatterns, %s%
MsgBox,, Tags Replaced, %	regex.Replace(haystack, "|")
Hamlet
Posts: 32
Joined: 02 Oct 2013, 09:55
Location: Seoul, Korea

Re: COM Object Reference

03 Oct 2013, 03:38

sinkfaze wrote:COM Object: VBSript.RegExp
Purpose: VBS Regular Expressions
System Requirements: General
Documentation Link: Regular Expression Object Properties and Methods
Personally, I'd like to recommend the following link.

Microsoft Beefs Up VBScript with Regular Expressions
http://msdn.microsoft.com/en-us/library/ms974570.aspx

Code: Select all

CNT =
(
123 abc 456 def
789 efgh 012 ijkl
)
REX  :=  ComObjCreate( "VBScript.RegExp" )
REX.Global  :=  True 
REX.IgnoreCase  :=  False
REX.Pattern  :=  "(\d+)\s*(\w+)"
COL  :=  REX.Execute( CNT)
Loop %  COL.Count
  LT1  .= COL.Item( A_Index - 1 ).Value  "`n"    ; Zero Based Offset
Loop %  COL.Count
  LT2  .= COL.Item( A_Index - 1 ).Submatches(0)
For EMT  in  COL
  LT3  .=  EMT.Value  "`n"
For EMT  in  COL
  LT4  .=  EMT.Submatches(1)
Msgbox % LT1 "`n`n" LT2 "`n`n" LT3  "`n`n"  LT4
Return
Last edited by Hamlet on 03 Oct 2013, 04:39, edited 2 times in total.

Return to “Scripts and Functions (v1)”

Who is online

Users browsing this forum: comvox, gwarble, IfThenElse and 129 guests