Fetching specific text from a dialog box using autoit - autoit

I want to get text from a dialog box. I am getting the title from the dialog box using winGetTitle() function.
My code in autoit is as follows:
$pId = Run("C:/foldername/Dialogbox.exe")
Local $hWnd = WinWait("[CLASS:#32770]", "", 10)
Local $sTitle = WinGetTitle("[ACTIVE]")
; Display the window title.
ConsoleWrite($sTitle & #CRLF)
; changing control from the class containg title to the class containing the text.
Local $hSysTray_Handle = ControlGetHandle('[Class:#32770]', '', '[Class:SysListView32;Instance:1]')
Local $sText = WinGetText("[ACTIVE]")
Local $sTextnew = ControlGetText($hSysTray_Handle, "", $sText)
ConsoleWrite($sTextnew & #CRLF)
This returns only the title and not the text in the dialog box. #32770 is the main class of dialog box and title, text are in the different classes in basic control info in autoit.
I am new to autoit and don't know how to fetch the text from dialog box. Or should I use sikuli for this?

; Start Mp3tag if not running.
If Not ProcessExists('Mp3tag.exe') Then
Run('"C:\Program Files (x86)\Mp3tag\Mp3tag.exe"')
If #error Then Exit 1
EndIf
; Scans working directory for Mp3 files.
WinWaitClose('Reading directory', '', 5)
; Main window.
$hWnd = WinWait('Mp3tag')
; Get item count of 1st column from the listview.
For $i1 = 1 To 5
$iCount = ControlListView($hWnd, '', 'SysListView321', 'GetItemCount')
If $iCount Then
ConsoleWrite('Found ' & $iCount & ' items.' & #CRLF)
ExitLoop
EndIf
Sleep(1000)
Next
If Not $iCount Then
MsgBox(0x40000, #ScriptName, 'Count is 0')
Exit 1
EndIf
; Get text of each listview item in the 1st column.
For $i1 = 0 To $iCount -1
$sText = ControlListView($hWnd, '', 'SysListView321', 'GetText', $i1)
ConsoleWrite(StringFormat('%3d Text: %s', $i1, $sText) & #CRLF)
Next
I do not have "C:/foldername/Dialogbox.exe" to test with.
I do have Mp3tag which has a SysListView32 control.
ControlListView() can get text etc. from a ListView control.
The parameter GetItemCount will get the count of list items
and GetText will get text from each list item.
This is test output:
Found 15 items.
0 Text: 01 - Lively Up Yourself.mp3
1 Text: 02 - Soul Rebel.mp3
2 Text: 03 - Treat Yourself Right.mp3
3 Text: 04 - Rebels Hop.mp3
4 Text: 05 - Soul Almighty.mp3
5 Text: 06 - Kaya.mp3
6 Text: 07 - Trenchtown Rock.mp3
7 Text: 08 - Soul Shakedown Party.mp3
8 Text: 09 - Natural Mystic.mp3
9 Text: 10 - Fussing And Fighting.mp3
10 Text: 11 - African Herbsman.mp3
11 Text: 12 - Keep On Moving.mp3
12 Text: 13 - Go Tell It On The Mountain.mp3
13 Text: 14 - How Many Times.mp3
14 Text: 15 - Bonus Track.mp3
The list item number is on the left
and the list item text is on the right,
following Text:.
At a guess, the code to test your Dialogbox.exe with:
Run("C:\foldername\Dialogbox.exe")
$hWnd = WinWait("[CLASS:#32770]", "", 10)
; Allow time for SysListView321 to fully load.
Sleep(1000)
; Get the window title.
$sTitle = WinGetTitle("[ACTIVE]")
ConsoleWrite($sTitle & #CRLF)
; Changing control from the class containing title to the class containing the text.
$hLView = ControlGetHandle($hWnd, '', 'SysListView321')
; Get item count of 1st column from the listview.
$iCount = ControlListView($hWnd, '', $hLView, 'GetItemCount')
; Get text of each listview item in the 1st column.
For $i1 = 0 To $iCount -1
$sText = ControlListView($hWnd, '', $hLView, 'GetText', $i1)
ConsoleWrite(StringFormat('%3d Text: %s', $i1, $sText) & #CRLF)
Next
It could use some improvement even if it works.

Related

How to know end of PDF File on Auto IT

I have an AutoIT script to open and scroll to end of PDF file by mouse action. By the number of times for scrolling is depended on the zoom percent and the number of pages. How do I determine the end of PDF file for configure the number of times for scrolling?
Below is the sample script. I fixed the number of times for scrolling is 15
Func OpenAllPDFFile($vardirectory)
If #error = 1 Then
MsgBox($MB_SYSTEMMODAL, "", "Path is invalid.", 2)
ElseIf #error = 4 Then
MsgBox($MB_SYSTEMMODAL, "", "No report(s) found.", 2)
ElseIf #error Then
MsgBox($MB_SYSTEMMODAL, "", "Fail to open report", 2)
Else
$FileArray = _FileListToArray($vardirectory, "*.pdf",1)
$NewFileArray = SortPDFFile($FileArray)
For $i = 0 To UBound($NewFileArray)-1
ShellExecute($vardirectory & "\" & $NewFileArray[$i])
ConsoleWrite("Opening pdf file: " & $NewFileArray[$i] & #CRLF)
if WinWaitActive($NewFileArray[$i]) Then
ConsoleWrite("Pdf file " & $NewFileArray[$i] & " is opened" & #CRLF)
WinSetState($NewFileArray[$i], "", #SW_MAXIMIZE)
Sleep($varSleep)
ControlClick($NewFileArray[$i], "", $varZoomPercent)
ControlSend($NewFileArray[$i], "", $varZoomPercent, $vPercent)
Send("{ENTER}")
Sleep($varSleep)
For $y = 0 To 15
If WinExists("[CLASS:AcrobatSDIWindow]") Then
MouseWheel($MOUSE_WHEEL_DOWN, 12)
Sleep($varSleepRead)
Else
ExitLoop
EndIf
Next
Else
ConsoleWrite("Could not find pdf file: " & #CRLF)
EndIf
WinClose("[CLASS:AcrobatSDIWindow]")
Next
EndIf
WinClose($varDUTPlot,"")
EndFunc
If you really just need to go to the end of the PDF I would use Page Down like this:
Send("{PGDN down}") # hold key down
Sleep(10000) # hold it for 10 sec
Send("{PGDN up}") # stop holding it
You can increase or lower the time just by editing the sleep time(in ms).
I don't know how to scale it with the PDF size.
If you know the pagecount it would be easy. ;)
$c = PAGES_IN_PDF
$t = $c * 200 # plan enough time for slow PCs
Sleep($t)

AutoIt Searching values to get class variable

I have a problem with searching and displaying only the values that I need. So basically I need to get a class name stored in a variable which depends on the selected item.
Every [section] of items has key 1 ( item name ), 78 ( race ), 80 ( class ).
78=1 ; human - race
80=1 ; knight - class
80=2 ; archer - class
80=8 ; mage - class
78=2 ; orc - race
80=1 ; berskerer - class
80=2 ; hunter - class
80=8 ; sorc - class
78=4 ; elf - race
80=1 ; swashbuckler - class
80=2 ; ranger - class
80=8 ; elementalist - class
78=8 ; dragonscion - race
80=15 ; scion - class
Here is my code: http://pastebin.com/DUwhVAxY
Here is zip file with 2 images and .ini file http://uploaded.net/file/eleih11o.
In the 1st image is my code that works, and in the 2nd image is an example of what I need; just a variable with class name.
Here is one more image with all the stuff:
This is the closest I could get but still it will fail since you have no standard seperators and/or items.
Case $hFinddAllButton
GUICtrlSetData($hList, '')
Redim $afound[0][3]
Local $sCout = 0
Local $sCounterText[0]
Local $sCounterNum[0]
For $i = 0 To UBound($matches)-1
If StringInStr($matches[$i][2], GUICtrlRead($hSearchInput)) Then
_ArrayAdd($afound, $matches[$i][0] &'|'& $matches[$i][1] &'|'& $matches[$i][2])
ReDim $sCounterText[UBound($sCounterText) +1]
ReDim $sCounterNum[UBound($sCounterNum) +1]
$sCounterText[$sCout] = $matches[$i][2]
$sCounterNum[$sCout] = $matches[$i][0]
$sCout += 1
EndIf
Next
For $s = 0 To UBound($sCounterText) -1
;~ ConsoleWrite($sCounterText[$s] & #LF)
;~ _ArrayAdd($afound, $matches[$i][0] &'|'& $matches[$i][1] &'|'& $matches[$i][2])
Local $sSplit = StringSplit($sCounterText[0], " ", 2)
Local $sSplit2 = StringSplit($sCounterText[$s], " ", 2)
GUICtrlSetData($hList, '[' & $sCounterNum[$s] &'] ' & $sSplit[0] & " Biltz (" & GUICtrlRead($hSearchInput) & ") - " & $sCounterText[$s])
Next

autoIt3 how to select n-th matched control?

When using autoIt to get Window's Text and the WinGetText matches multiple controls (e.g. with the same Class SciCalc in this case), the WinGetText will concatenate the text of all the controls. How can I get the Text of the n-th (say 3rd 'MR') control?
e.g.
Local $output = WinGetText("[CLASS:SciCalc]", "")
print
output:666666.
MC
MR
MS
M+
7
4
1
0
8
5
2
+/-
9
6
3
.
/
*
-
+
=
Backspace
CE
C
1/x
sqt
%
Something like this
ControlGetText("[CLASS:SciCalc]","","[CLASS:Button; INSTANCE:3]")
Use AutoIt Window Info to find the Advanced mode details on the wanted control.

Get a list of all open windows using AutoIt

I'm trying to get rid of my minimize, maximize and close buttons on all windows. Googling around I found this:
$h = WinGetHandle("[CLASS:Notepad]")
$iOldStyle = _WinAPI_GetWindowLong($h, $GWL_STYLE)
$iNewStyle = BitXOr($iOldStyle, $WS_SYSMENU)
_WinAPI_SetWindowLong($h, $GWL_STYLE, $iNewStyle)
_WinAPI_ShowWindow($h, #SW_SHOW)
This works fine, so now I only need to iterate over all windows with this code, and I'm done. How do I get a list of all HWNDs in the system?
You can get a list of all open windows using WinList:
$aWindows = WinList()
For $i=1 To $aWindows[0][0]
; skip windows without a title
If $aWindows[$i][0] = '' Then ContinueLoop
;use the HWND to get the state of the window
$iWndState = WinGetState($aWindows[$i][1])
; here you could filter out the windows you don't want to modify
ConsoleWrite($aWindows[$i][0] & ': ')
If BitAND($iWndState,1) = 1 Then ConsoleWrite(' exists')
If BitAND($iWndState,2) = 2 Then ConsoleWrite(' visible')
If BitAND($iWndState,4) = 4 Then ConsoleWrite(' enabled')
If BitAND($iWndState,8) = 8 Then ConsoleWrite(' active')
If BitAND($iWndState,16) = 16 Then ConsoleWrite(' minimised')
If BitAND($iWndState,32) = 32 Then ConsoleWrite(' maximised')
ConsoleWrite(#CRLF)
Next

Can openoffice count words from console?

i have a small problem i need to count words inside the console to read doc, docx, pptx, ppt, xls, xlsx, odt, pdf ... so don't suggest me | wc -w or grep because they work only with text or console output and they count only spaces and in japanese, chinese, arabic , hindu , hebrew they use diferent delimiter so the word count is wrong and i tried to count with this
pdftotext file.pdf -| wc -w
/usr/local/bin/docx2txt.pl < file.docx | wc -w
/usr/local/bin/pptx2txt.pl < file.pptx | wc -w
antiword file.doc -| wc -w
antiword file.word -| wc -w
in some cases microsoft word , openoffice sad 1000 words and the counters return 10 or 300 words if the language is ( japanese , chinese, hindu ect... ) , but if i use normal characters then i have no issue the biggest mistake is in some case 3 chars less witch is "OK"
i tried to convert with soffice , openoffice and then try WC -w but i can't even convert ,
soffice --headless --nofirststartwizard --accept=socket,host=127.0.0.1,port=8100; --convert-to pdf some.pdf /var/www/domains/vocabridge.com/devel/temp_files/23/0/东京_1000_words_Docx.docx
OR
openoffice.org --headless --convert-to ........
OR
openoffice.org3 --invisible
so if someone know any way to count correctly or display document statistic with openoffice or anything else or linux with the console please share it
thanks.
If you have Microsoft Word (and Windows, obviously) you can write a VBA macro or if you want to run straight from the command line you can write a VBScript script with something like the following:
wordApp = CreateObject("Word.Application")
doc = ... ' open up a Word document using wordApp
docWordCount = doc.Words.Count
' Rinse and repeat...
If you have OpenOffice.org/LibreOffice you have similar (but more) options. If you want to stay in the office app and run a macro you can probably do that. I don't know the StarBasic API well enough to tell you how but I can give you the alternative: creating a Python script to get the word count from the command line. Roughly speaking, you do the following:
Start up your copy of OOo/LibO from the command line with the appropriate parameters to accept incoming socket connections. http://www.openoffice.org/udk/python/python-bridge.html has instructions on how to do that. Go there and use the browser's in-page find feature to search for `accept=socket'
Write a Python script to use the OOo/LibO UNO bridge (basically equivalent to the VBScript example above) to open up your Word/ODT documents one at a time and get the word count from each. The above page should give you a good start to doing that.
You get the word count from a document model object's WordCount property: http://www.openoffice.org/api/docs/common/ref/com/sun/star/text/GenericTextDocument.html#WordCount
Just building on to what #Yawar wrote. Here is is more explicit steps for how to word count with MS word from the console.
I also use the more accurate Range.ComputeStatistics(wdStatisticWords) instead of the Words property. See here for more info: https://support.microsoft.com/en-za/help/291447/word-count-appears-inaccurate-when-you-use-the-vba-words-property
Make a script called wc.vbs and then put this in it:
Set word = CreateObject("Word.Application")
word.Visible = False
Set doc = word.Documents.Open("<replace with absolute path to your .docx/.pdf>")
docWordCount = doc.Range.ComputeStatistics(wdStatisticWords)
word.Quit
Dim StdOut : Set StdOut = CreateObject("Scripting.FileSystemObject").GetStandardStream(1)
WScript.Echo docWordCount & " words"
Open powershell in the directory you saved wc.vbs and run cscript .\wc.vbs and you'll get back the word count :)
I think this may do what you are aiming for
# Continuously updating word count
import unohelper, uno, os, time
from com.sun.star.i18n.WordType import WORD_COUNT
from com.sun.star.i18n import Boundary
from com.sun.star.lang import Locale
from com.sun.star.awt import XTopWindowListener
#socket = True
socket = False
localContext = uno.getComponentContext()
if socket:
resolver = localContext.ServiceManager.createInstanceWithContext('com.sun.star.bridge.UnoUrlResolver', localContext)
ctx = resolver.resolve('uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext')
else: ctx = localContext
smgr = ctx.ServiceManager
desktop = smgr.createInstanceWithContext('com.sun.star.frame.Desktop', ctx)
waittime = 1 # seconds
def getWordCountGoal():
doc = XSCRIPTCONTEXT.getDocument()
retval = 0
# Only if the field exists
if doc.getTextFieldMasters().hasByName('com.sun.star.text.FieldMaster.User.WordCountGoal'):
# Get the field
wordcountgoal = doc.getTextFieldMasters().getByName('com.sun.star.text.FieldMaster.User.WordCountGoal')
retval = wordcountgoal.Content
return retval
goal = getWordCountGoal()
def setWordCountGoal(goal):
doc = XSCRIPTCONTEXT.getDocument()
if doc.getTextFieldMasters().hasByName('com.sun.star.text.FieldMaster.User.WordCountGoal'):
wordcountgoal = doc.getTextFieldMasters().getByName('com.sun.star.text.FieldMaster.User.WordCountGoal')
wordcountgoal.Content = goal
# Refresh the field if inserted in the document from Insert > Fields >
# Other... > Variables > Userdefined fields
doc.TextFields.refresh()
def printOut(txt):
if socket: print txt
else:
model = desktop.getCurrentComponent()
text = model.Text
cursor = text.createTextCursorByRange(text.getEnd())
text.insertString(cursor, txt + '\r', 0)
def hotCount(st):
'''Counts the number of words in a string.
ARGUMENTS:
str st: count the number of words in this string
RETURNS:
int: the number of words in st'''
startpos = long()
nextwd = Boundary()
lc = Locale()
lc.Language = 'en'
numwords = 1
mystartpos = 1
brk = smgr.createInstanceWithContext('com.sun.star.i18n.BreakIterator', ctx)
nextwd = brk.nextWord(st, startpos, lc, WORD_COUNT)
while nextwd.startPos != nextwd.endPos:
numwords += 1
nw = nextwd.startPos
nextwd = brk.nextWord(st, nw, lc, WORD_COUNT)
return numwords
def updateCount(wordCountModel, percentModel):
'''Updates the GUI.
Updates the word count and the percentage completed in the GUI. If some
text of more than one word is selected (including in multiple selections by
holding down the Ctrl/Cmd key), it updates the GUI based on the selection;
if not, on the whole document.'''
model = desktop.getCurrentComponent()
try:
if not model.supportsService('com.sun.star.text.TextDocument'):
return
except AttributeError: return
sel = model.getCurrentSelection()
try: selcount = sel.getCount()
except AttributeError: return
if selcount == 1 and sel.getByIndex(0).getString == '':
selcount = 0
selwords = 0
for nsel in range(selcount):
thisrange = sel.getByIndex(nsel)
atext = thisrange.getString()
selwords += hotCount(atext)
if selwords > 1: wc = selwords
else:
try: wc = model.WordCount
except AttributeError: return
wordCountModel.Label = str(wc)
if goal != 0:
pc_text = 100 * (wc / float(goal))
#pc_text = '(%.2f percent)' % (100 * (wc / float(goal)))
percentModel.ProgressValue = pc_text
else:
percentModel.ProgressValue = 0
# This is the user interface bit. It looks more or less like this:
###############################
# Word Count _ o x #
###############################
# _____ #
# 451 / |500| #
# ----- #
# ___________________________ #
# |############## | #
# --------------------------- #
###############################
# The boxed `500' is the text entry box.
class WindowClosingListener(unohelper.Base, XTopWindowListener):
def __init__(self):
global keepGoing
keepGoing = True
def windowClosing(self, e):
global keepGoing
keepGoing = False
setWordCountGoal(goal)
e.Source.setVisible(False)
def addControl(controlType, dlgModel, x, y, width, height, label, name = None):
control = dlgModel.createInstance(controlType)
control.PositionX = x
control.PositionY = y
control.Width = width
control.Height = height
if controlType == 'com.sun.star.awt.UnoControlFixedTextModel':
control.Label = label
elif controlType == 'com.sun.star.awt.UnoControlEditModel':
control.Text = label
elif controlType == 'com.sun.star.awt.UnoControlProgressBarModel':
control.ProgressValue = label
if name:
control.Name = name
dlgModel.insertByName(name, control)
else:
control.Name = 'unnamed'
dlgModel.insertByName('unnamed', control)
return control
def loopTheLoop(goalModel, wordCountModel, percentModel):
global goal
while keepGoing:
try: goal = int(goalModel.Text)
except: goal = 0
updateCount(wordCountModel, percentModel)
time.sleep(waittime)
if not socket:
import threading
class UpdaterThread(threading.Thread):
def __init__(self, goalModel, wordCountModel, percentModel):
threading.Thread.__init__(self)
self.goalModel = goalModel
self.wordCountModel = wordCountModel
self.percentModel = percentModel
def run(self):
loopTheLoop(self.goalModel, self.wordCountModel, self.percentModel)
def wordCount(arg = None):
'''Displays a continuously updating word count.'''
dialogModel = smgr.createInstanceWithContext('com.sun.star.awt.UnoControlDialogModel', ctx)
dialogModel.PositionX = XSCRIPTCONTEXT.getDocument().CurrentController.Frame.ContainerWindow.PosSize.Width / 2.2 - 105
dialogModel.Width = 100
dialogModel.Height = 30
dialogModel.Title = 'Word Count'
lblWc = addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 6, 2, 25, 14, '', 'lblWc')
lblWc.Align = 2 # Align right
addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 33, 2, 10, 14, ' / ')
txtGoal = addControl('com.sun.star.awt.UnoControlEditModel', dialogModel, 45, 1, 25, 12, '', 'txtGoal')
txtGoal.Text = goal
#addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 6, 25, 50, 14, '(percent)', 'lblPercent')
ProgressBar = addControl('com.sun.star.awt.UnoControlProgressBarModel', dialogModel, 6, 15, 88, 10,'' , 'lblPercent')
ProgressBar.ProgressValueMin = 0
ProgressBar.ProgressValueMax =100
#ProgressBar.Border = 2
#ProgressBar.BorderColor = 255
#ProgressBar.FillColor = 255
#ProgressBar.BackgroundColor = 255
addControl('com.sun.star.awt.UnoControlFixedTextModel', dialogModel, 124, 2, 12, 14, '', 'lblMinus')
controlContainer = smgr.createInstanceWithContext('com.sun.star.awt.UnoControlDialog', ctx)
controlContainer.setModel(dialogModel)
controlContainer.addTopWindowListener(WindowClosingListener())
controlContainer.setVisible(True)
goalModel = controlContainer.getControl('txtGoal').getModel()
wordCountModel = controlContainer.getControl('lblWc').getModel()
percentModel = controlContainer.getControl('lblPercent').getModel()
ProgressBar.ProgressValue = percentModel.ProgressValue
if socket:
loopTheLoop(goalModel, wordCountModel, percentModel)
else:
uthread = UpdaterThread(goalModel, wordCountModel, percentModel)
uthread.start()
keepGoing = True
if socket:
wordCount()
else:
g_exportedScripts = wordCount,
Link for more info
https://superuser.com/questions/529446/running-word-count-in-openoffice-writer
Hope this helps regards tom
EDIT : Then i found this
http://forum.openoffice.org/en/forum/viewtopic.php?f=7&t=22555
wc can understand Unicode and uses system's iswspace function to find whether the unicode character is whitespace. "The iswspace() function tests whether wc is a wide-character code representing a character of class space in the program's current locale." So, wc -w should be able to correctly count words if your locale (LC_CTYPE) is configured correctly.
The source code of the wc program
The manual page for the iswspace function
I found the answer create one service
#!/bin/sh
#
# chkconfig: 345 99 01
#
# description: your script is a test service
#
(while sleep 1; do
ls pathwithfiles/in | while read file; do
libreoffice --headless -convert-to pdf "pathwithfiles/in/$file" --outdir pathwithfiles/out
rm "pathwithfiles/in/$file"
done
done) &
then the php script that i needed counted everything
$ext = pathinfo($absolute_file_path, PATHINFO_EXTENSION);
if ($ext !== 'txt' && $ext !== 'pdf') {
// Convert to pdf
$tb = mktime() . mt_rand();
$tempfile = 'locationofpdfs/in/' . $tb . '.' . $ext;
copy($absolute_file_path, $tempfile);
$absolute_file_path = 'locationofpdfs/out/' . $tb . '.pdf';
$ext = 'pdf';
while (!is_file($absolute_file_path)) sleep(1);
}
if ($ext !== 'txt') {
// Convert to txt
$tempfile = tempnam(sys_get_temp_dir(), '');
shell_exec('pdftotext "' . $absolute_file_path . '" ' . $tempfile);
$absolute_file_path = $tempfile;
$ext = 'txt';
}
if ($ext === 'txt') {
$seq = '/[\s\.,;:!\? ]+/mu';
$plain = file_get_contents($absolute_file_path);
$plain = preg_replace('#\{{{.*?\}}}#su', "", $plain);
$str = preg_replace($seq, '', $plain);
$chars = count(preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY));
$words = count(preg_split($seq, $plain, -1, PREG_SPLIT_NO_EMPTY));
if ($words === 0) return $chars;
if ($chars / $words > 10) $words = $chars;
return $words;
}

Resources