COM Object Reference

Post a reply

Confirmation code
Enter the code exactly as it appears. All letters are case insensitive.
Smilies
:D :) ;) :( :o :shock: :? 8-) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :!: :?: :idea: :| :mrgreen: :geek: :ugeek: :arrow: :angel: :clap: :crazy: :eh: :lolno: :problem: :shh: :shifty: :sick: :silent: :think: :thumbup: :thumbdown: :salute: :wave: :wtf: :yawn: :facepalm: :bravo: :dance: :beard: :morebeard: :xmas: :HeHe: :trollface: :cookie: :rainbow: :monkeysee: :monkeysay: :happybday: :headwall: :offtopic: :superhappy: :terms: :beer:
View more smilies

BBCode is ON
[img] is OFF
[flash] is OFF
[url] is ON
Smilies are ON

Topic review
   

Expand view Topic review: COM Object Reference

Re: COM Object Reference

by guesto » 10 Apr 2016, 14:32

sinkfaze wrote: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:
I have installed ImageMagick with the COM option in the installer (the checkbox about VBS something, don't remember exactly). I can run the ImageMagickObject .vbs test script that comes with ImageMagick. But I can't get it to work in AHK. The sample script generated "Invalid class string" error on this line

Code: Select all

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

Re: COM Object Reference

by Joe Glines » 18 Jul 2015, 11:09

Joetazz wrote:Any idea what the maximum size that can be stored in this? I read through some of the documentation however I was playing around and was storing a lot more characters than what I saw in the documentation.


I reached a max of 524,285 charchters on my 64 bit version of Windows 7

Re: COM Object Reference

by Joe Glines » 17 Jul 2015, 19:08

Any idea what the maximum size that can be stored in this? I read through some of the documentation however I was playing around and was storing a lot more characters than what I saw in the documentation.
sinkfaze wrote:COM Object: WScript.Shell
Purpose: Exchange variables between scripts
System Requirements: General
Documentation Link: WshEnvironment Object
Other Links: Environment Variables

Re: COM Object Reference

by joedf » 11 Jan 2015, 13:15

Hello asynchronous downloads!

Re: COM Object Reference

by lexikos » 11 Jan 2015, 03:20

COM Object: Msxml2.XMLHTTP, a.k.a. XmlHttpRequest object.
Purpose: Making HTTP requests. Unlike UrlDownloadToFile, it doesn't require managing a temporary file. Unlike WinHttpRequest, it can notify us when the request is complete.
System Requirements: IE7+ and AutoHotkey v1.1.17+ to use onreadystatechange.
Documentation Link: XMLHttpRequest object
Basic Code Example:

Code: Select all

req := ComObjCreate("Msxml2.XMLHTTP")
; Open a request with async enabled.
req.open("GET", "https://autohotkey.com/download/1.1/version.txt", true)
; Set our callback function (v1.1.17+).
req.onreadystatechange := Func("Ready")
; Send the request.
req.send()
/*
; If you're going to wait, there's no need for onreadystatechange.
; Setting async=true and waiting like this allows the script to remain
; responsive while the download is taking place, whereas async=false
; will make the script unresponsive.
while req.readyState != 4
    sleep 100
*/
#Persistent

Ready() {
    global req
    if (req.readyState != 4)  ; Not done yet.
        return
    if (req.status == 200 || req.status == 304) ; OK.
        MsgBox % "Latest AutoHotkey version: " req.responseText
    else
        MsgBox 16,, % "Status " req.status
    ExitApp
}
I started looking into this because using WinHttpRequest in synchronous mode causes the script to hang until the request completes, but it turns out you can get around that by opening the request in asynchronous mode and calling WinHttpRequest.WaitForResponse(). The advantages of XMLHTTP are that the API is well known to many web developers, and the events (like onreadystatechange) are compatible with AutoHotkey.

Re: COM Object Reference

by GeekDude » 07 Nov 2014, 08:32

Wouldn't this be better suited to a GitHub repository or something along those lines? Perhaps under the AhkScript group?

Re: COM Object Reference

by kon » 06 Nov 2014, 18:42

COM Object: Publisher.Application
Purpose: Microsoft Publisher is an entry-level desktop publishing application from Microsoft, differing from Microsoft Word in that the emphasis is placed on page layout and design rather than text composition and proofing.
System Requirements: Microsoft Office Publisher
Documentation Link: Object model reference (Publisher 2013 developer reference)
Other Links: Save the active document as .jpg
Basic Code Example: This example will open Publisher, create a new document, draw a curve and a line, add some text, and SaveAs with two different formats (.jpg and .pub).

Code: Select all

; Constants
msoTrue := -1
pbPictureResolutionCommercialPrint_300dpi := 3
pbTextOrientationHorizontal := 1
VT_R4 := 4  ; 32-bit floating-point number

pbApp := ComObjCreate("Publisher.Application")      ; Create a Publisher application object and store a reference to it in the pbApp variable
pbApp.ActiveWindow.Visible := true                  ; Make the window visible

; Application.NewDocument Method (Publisher)
; http://msdn.microsoft.com/en-us/library/office/ff940013%28v=office.15%29.aspx
pbDoc := pbApp.NewDocument()                        ; Create a new document and store a reference to the object in the pbDoc variable

; Shapes Methods (Publisher)
; http://msdn.microsoft.com/en-us/library/office/dn338310%28v=office.15%29.aspx
pbDoc.Pages(1).Shapes.AddLine(100, 150, 500, 550)   ; Draw a line from the point (100, 150) to point (500, 550)

; Shapes.AddCurve Method (Publisher)
; http://msdn.microsoft.com/en-us/library/office/ff939838%28v=office.15%29.aspx
arrPoints := ComObjArray(VT_R4, 4, 2)
arrPoints[0, 0] := 100
arrPoints[0, 1] := 150
arrPoints[1, 0] := 240
arrPoints[1, 1] := 600
arrPoints[2, 0] := 370
arrPoints[2, 1] := 100
arrPoints[3, 0] := 500
arrPoints[3, 1] := 550
pbDoc.Pages(1).Shapes.AddCurve(arrPoints)           ; Draw a curve using the points specified by the array

; Shapes.AddTextbox Method (Publisher)
; http://msdn.microsoft.com/en-us/library/office/ff939294%28v=office.15%29.aspx
pbTextbox := pbDoc.Pages(1).Shapes.AddTextbox(pbTextOrientationHorizontal, 40, 60, 520, 65)  ; Create a textbox
; Story.TextRange Property (Publisher)
; http://msdn.microsoft.com/en-us/library/office/ff940334%28v=office.15%29.aspx
pbTextRange := pbTextbox.TextFrame.Story.TextRange  ; Store a reference to the range of text inside the textbox
pbTextRange.Text := "AutoHotkey is awesome!"
pbTextRange.Font.Bold := msoTrue
pbTextRange.Font.Size := 40
pbTextRange.Font.Name := "Arial"

; Page.SaveAsPicture Method (Publisher)
; http://msdn.microsoft.com/en-us/library/office/ff939984%28v=office.15%29.aspx
SavePath := A_ScriptDir "\MyTestFile.jpg"           ; Save the picture to the same directory as this script
pbDoc.Pages(1).SaveAsPicture(SavePath, pbPictureResolutionCommercialPrint_300dpi)

; Document.SaveAs Method (Publisher)
; http://msdn.microsoft.com/en-us/library/office/ff940221%28v=office.15%29.aspx
SavePath := A_ScriptDir "\MyTestDocument.pub"       ; Save the document to the same directory as this script
pbDoc.SaveAs(SavePath)
return

Re: COM Object Reference

by kon » 15 Jul 2014, 14:50

A remake of the index.
Index

Re: COM Object Reference

by Menixator » 03 Oct 2013, 04:13

Re: COM Object Reference

by joedf » 03 Oct 2013, 04:09

Interesting..

Re: COM Object Reference

by Hamlet » 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

Re: COM Object Reference

by sinkfaze » 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, "|")

Re: COM Object Reference

by sinkfaze » 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.

Re: COM Object Reference

by sinkfaze » 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

Re: COM Object Reference

by sinkfaze » 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()

Re: COM Object Reference

by sinkfaze » 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
}

Re: COM Object Reference

by sinkfaze » 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)

Re: COM Object Reference

by sinkfaze » 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.

Re: COM Object Reference

by sinkfaze » 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)
}

Re: COM Object Reference

by sinkfaze » 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

Top