I have many word templates and in my ahk-program, i would like to show small preview of them. So I thought I would write a script that opens each word document, selects the text and makes a screencapture of where it is shown on screen, to be saved as .png File. Seemed easy because I had all components already working in other parts of my program...
Anyway, this is the code that I use
Code: Select all
; creates PNG-Previews of all report templates
CreateTemplatePreviews() {
global TemplateFilePaths
myWord := ComObjCreate("Word.Application")
myWord.Documents.Add
myWord.Visible := 1
myWord.Activate
; myWord := ""
; anotherWord := ComObjActive("Word.Application")
Loop, Parse, TemplateFilePaths, `n
{
if (A_LoopField == "")
continue
SplitPath, A_LoopField, docName, docDir
myWord.Documents.Open(A_LoopField)
SetTitleMatchMode, 2
WinWait, %docName%
myWord.ActiveDocument.Select
Sleep, 1000
getWordVisibleTextScreenPosition(myWord, ByRef selX, ByRef sely, ByRef selW, ByRef selH)
; getWordFullRangeScreenPosition(myWord, ByRef selX, ByRef sely, ByRef selW, ByRef selH)
; getWordSelectionScreenPosition(myWord, ByRef selX, ByRef selY, ByRef selW, ByRef selH)
; getWordVisibleTextScreenPosition(myWord, ByRef selX, ByRef selY, ByRef selW, ByRef selH)
MsgBox, done. selX:%selX% selY:%sely% selW:%selW% selH:%selH%
; ... more code to capture screen region and save to some directory
myWord.ActiveDocument.Close
}
MsgBox, test
}
Code: Select all
; determines the position of the visible text in word on screen
getWordVisibleTextScreenPosition(wordComObj, ByRef selX, ByRef sely, ByRef selW, ByRef selH) {
OutputDebug, getWordVisibleTextScreenPosition(wordComObj, ByRef selX, ByRef sely, ByRef selW, ByRef selH)`n
aRange := wordComObj.Selection.Range
addingSentence := true
expandedChars := 1
while (addingSentence && (expandedChars > 0)) {
Try
{
aBiggerRange := aRange
expandedChars := aBiggerRange.Expand(3) ; expand range to whole sentence! 3=wbSentence, returns the amount of characters expanded
type := (VT_BYREF := 0x4000) | (VT_I4 := 0x3) ; fit the type
VarSetCapacity(buff, 16, 0) ; long int
for k, v in ["selX", "selY", "selW", "selH"]
%v% := ComObject(type, &buff + (k - 1)*4)
wordComObj.ActiveWindow.GetPoint(selX, selY, selW, selH, aRange) ; this throws an error when aRange is not completely visible on screen
} catch {
addingSentence := false
MsgBox, Error thrown
break
}
aRange := aBiggerRange
}
for k, v in ["selX", "selY", "selW", "selH"] ; fill variables
%v% := %v%[]
}