Logitech Lua: Toggle between actions using modifier - random

I got a problem with this script and can't find a solution (if there is one). Would be great to find some help here!
Is it possible to toggle between the two repeated events (Mb5 without modifier "lshift" and Mb5 with modifier "lshift") only by pressing or releasing the "lshift" key?
Goal: Holding down Mb5 -> repeat action with "8" and "7" -> Keep holding down Mb5 + pressing modifier "lshift" -> repeat action with "r" and "e" -> releasing "lshift" -> back to repeating "8" and "7"
Problem: Script stops repeating "8" and "7" when pressing "lshift" but wont start repeating "r" and "e" and the other way around.
btw. this is not a final script but to showcase the problem.
EnablePrimaryMouseButtonEvents(true)
function OnEvent(event, arg)
if event == "MOUSE_BUTTON_PRESSED" and arg == 5 and not IsModifierPressed("lshift") then
repeat
local key1 = ({"8", "8"})[math.random(2)]
local key2 = ({"7", "7"})[math.random(2)]
if not IsMouseButtonPressed(5) then break end
Sleep(math.random(17, 34))
PressKey(key1)
Sleep(math.random(17, 34))
PressKey(key2)
Sleep(math.random(41, 85))
ReleaseKey(key1)
Sleep(math.random(41, 85))
ReleaseKey(key2)
until not IsMouseButtonPressed(5) or IsModifierPressed("lshift")
elseif event == "MOUSE_BUTTON_PRESSED" and arg == 5 and IsModifierPressed("lshift") then
repeat
if not IsMouseButtonPressed(5) then break end
Sleep(math.random(17, 34))
PressKey("r")
Sleep(math.random(41, 85))
ReleaseKey("r")
Sleep(math.random(17, 34))
PressKey("e")
Sleep(math.random(41, 85))
ReleaseKey("e")
until not IsMouseButtonPressed(5) or not IsModifierPressed("lshift")

I was thinking for 5 months on your question :-)
function OnEvent(event, arg)
if event == "PROFILE_ACTIVATED" then
EnablePrimaryMouseButtonEvents(true)
elseif event == "MOUSE_BUTTON_PRESSED" and arg == 5 then
repeat
if not IsModifierPressed("lshift") then
local key1 = ({"8", "8"})[math.random(2)]
local key2 = ({"7", "7"})[math.random(2)]
Sleep(math.random(17, 34))
PressKey(key1)
Sleep(math.random(17, 34))
PressKey(key2)
Sleep(math.random(41, 85))
ReleaseKey(key1)
Sleep(math.random(41, 85))
ReleaseKey(key2)
end
if IsModifierPressed("lshift") then
Sleep(math.random(17, 34))
PressKey("r")
Sleep(math.random(41, 85))
ReleaseKey("r")
Sleep(math.random(17, 34))
PressKey("e")
Sleep(math.random(41, 85))
ReleaseKey("e")
end
until not IsMouseButtonPressed(5)
end
end

Related

Logitech G105 keyboard start script

How can I start the script with a normal key, not a G-key?
Like SHIFT+K or just K.
local function interruptable_sleep(delay)
local tm = GetRunningTime() + delay
repeat
if IsKeyLockOn("scrolllock") then return true end
local t = tm - GetRunningTime()
if t > 0 then Sleep(math.min(t, 100)) end
until t <= 0
end
function OnEvent(event, arg)
if event=="G_PRESSED" and arg==3 then --This change for "K" or something not a G-Key

Adding a feature to this Hangman Game

I have a hangman game and I am having trouble adding in a feature. I want to make it if the whole word is guessed, it will display "You guessed the word!!!", but I cant seem to find a spot to put it. This is the code
hangman's init()
script hangman
property stdin : missing value
property stdout : missing value
property dict : missing value
on init()
--starting up the game
set stdin to parent's hangmanStdin's alloc()'s init()
set stdout to parent's hangmanStdout's alloc()'s init()
set dict to parent's hangmanDictionary's alloc()'s init()
my mainLoop()
end init
on mainLoop()
repeat --endless
set option to stdin's getOptions("Lobby", "What would you like to do?", {"New Game", "Quit"})
if option is "New Game" then
set difficulty to stdin's getOptions("New Game", "Choose your difficulty", {"Normal", "Easy", "Hard"})
--replace this line with an automatic word generator
set x to parent's hangmanGame's alloc()'s initWithWordAndDifficulty(dict's getWord(), difficulty)
if x's startgame() is false then
return
else
stdout's printf("You've scored " & x's score & " points.")
end if
--game is over so clear it
set x to missing value
else
exit repeat
end if
end repeat
end mainLoop
on shouldTerminate()
return true
end shouldTerminate
on alloc()
copy me to x
return x
end alloc
end script
script hangmanGame
property parent : hangman
property wordToGuess : missing value
property maxFaults : missing value
property usedChars : missing value
property faults : missing value
property score : 0
on initWithWordAndDifficulty(theWord, theDifficulty)
if theDifficulty = "Hard" then
set my maxFaults to 5
else if theDifficulty = "Normal" then
set my maxFaults to 8
else --easy or any other value will be handled as easy
set my maxFaults to 10
end if
set my wordToGuess to theWord
set my usedChars to {}
set my faults to 0
set my score to 0
return me
end initWithWordAndDifficulty
on startgame()
repeat --endless
set __prompt to "Faults Left: " & maxFaults - faults & return & "The Word: " & my makeHiddenField()
set c to parent's stdin's getChar(__prompt)
if c = false then
return false
end if
--first check if getChar did give us any result
if length of c is not 0 then
--check if teh character is valid
if c is in "abcdefghijklmnopqrstuvwxyz" then
--check if we already checked this before
if c is not in my usedChars then
set end of my usedChars to c
--check if player guessed wrong character
if c is not in wordToGuess then
set faults to faults + 1
end if
end if
end if
end if
--check if player guessed all characters of word
if my wordGuessed() then
set my score to ((25 * (26 / (length of my usedChars))) as integer)
return true
end if
--check if player reached the max faults he's allowed to make
if my faults = my maxFaults then
display dialog "The word was " & quoted form of wordToGuess
return 0
end if
end repeat
end startgame
on wordGuessed()
repeat with aChar in every text item of my wordToGuess
if aChar is not in my usedChars then
return false
end if
end repeat
return true
end wordGuessed
on makeHiddenField()
set characterArray to {}
repeat with aChar in every text item of my wordToGuess
if aChar is in my usedChars then
set end of characterArray to aChar as string
else
set end of characterArray to "_"
end if
end repeat
set AppleScript's text item delimiters to space
set hiddenField to characterArray as string
set AppleScript's text item delimiters to ""
return hiddenField
end makeHiddenField
end script
script hangmanDictionary
property parent : hangman
property wordsPlayed : missing value
property allWords : missing value
on init()
set wordsPlayed to {}
--try to get more words from a file for example
set allWords to {"Hangman", "Police", "Officer", "Desktop", "Pencil", "Window", "Language", "Wealthy", "Trauma", "Spell", "Rival", "Tactical", "Thin", "Salty", "Bluish", "Falcon", "Distilery", "Ballistics", "Fumbling", "Limitless", "South", "Humble", "Foreign", "Affliction", "Retreat", "Agreeable", "Poisoner", "Flirt", "Fearsome", "Deepwater", "Bottom", "Twisted", "Morsel", "Filament", "Winter", "Contempt", "Drimys", "Grease", "Awesome", "Compulsive", "Crayon", "Prayer", "Blonde", "Backbone", "Dreamland", "Ballet", "Continuous", "Aerobatic", "Hideous", "Harmonic", "Lottery", "Encrypt", "Cable", "Aluminium", "Hunter", "National", "Hunter", "Mechanical", "Deadbeat", "Opposition", "Threat", "Decadent", "Gazelle", "Guild", "Authoritive", "Deliverance", "Severe", "Jerid", "Alarm", "Monochrome", "Cyanide", "External", "Potential", "Section", "Innocent", "Drifting", "Amnesia", "Domino", "Flimsy", "Flamethrowing", "Advocate", "Hirsute", "Brother", "Ephemeral", "Brutal", "Decade", "Drauma", "Dilemma", "Exquisite", "Glimmer", "Fugitive", "Digital", "Associate", "Ambivalent", "Ambulatory", "Apology", "Brawler", "Molecular", "Insurance", "Contractual", "Initial", "Calibration", "Heretical", "Disclosure", "Guerilla", "Dismember", "Minimal", "Altercation", "Eastern", "Integrate", "Femur", "Metallic", "Ambition", "Auxiliary", "Esoteric", "Converse", "Accepting", "Juvenile", "Efficacious", "Complex", "Imperil", "Division", "Onerous", "Astonish", "Scandalous", "Quaint", "Dominate", "Contrary", "Conspiracy", "Earthquake", "Embarrassment", "Exclude", "Ambiguous", "Captivate", "Compliance", "Migration", "Embryo", "Abandon", "Conservation", "Appreciate", "Applaud", "Pension", "Voyage", "Influence", "Consensus", "Incapable", "Economy", "Parameter", "Contrast", "Sensitive", "Meadow", "Chimney", "Familiar", "Serious", "Credibility", "Infrastructure", "Museum", "Relinquish", "Merit", "Coalition", "Retirement", "Transaction", "Official", "Composer", "Magnitude", "Committee", "Privilege", "Diamond", "Obligation", "Transition", "Jockey", "Reinforce", "Conflict", "Offensive", "Detective", "Effective", "Detector", "Abhorrent", "Fragile", "Feigned", "Addition", "Jealous", "Irritating", "Grotesque", "Hesitant", "Adaptable", "Highfalutin", "Defiant", "Ceaseless", "Aquatic", "Voracious", "Separate", "Phobic", "Scientific", "Cluttered", "Intelligent", "Garrulous", "Rhetorical", "Obtainable", "Bawdy", "Outstanding", "Synonymous", "Gleaming", "Ambitious", "Agonizing", "Fallacious", "Lamister", "Fugitive", "Individualism", "Archaic", "Paramount", "Pannose", "Pretermit", "Retorse", "Versability", "Demonomancy", "Vagile", "Reflation", "Foliate", "Guignol", "Agacerie", "Theopneustic", "Glumiferous", "Optative", "Scrivello", "Unifarious", "Ordonnance", "Dithyrambic", "Locative", "Locomotive", "Mirabilia", "Keyline", "Mellification", "Theomicrist", "Ireless", "Commonition", "Dragoon", "Webster", "Utinam", "Obumbrate", "Inceptive"}
return me
end init
on getWord()
set randomNr to (random number from 1 to (length of (my allWords))) as integer
--you could do somethinh here when a word is used again
return item randomNr of my allWords as string
end getWord
end script
script hangmanStdin
property parent : hangman
on init()
return me
end init
on getChar(__prompt)
set x to display dialog __prompt buttons {"Go", "Quit"} default button "Go" default answer ""
if button returned of x = "Quit" then
return false
end if
if length of x's text returned = 0 then
return ""
end if
return character 1 of x's text returned
end getChar
on getOptions(__title, __message, __options)
return button returned of (display alert __title message __message buttons __options default button 1)
end getOptions
end script
script hangmanStdout
property parent : hangman
on init()
return me
end init
on printf(__message)
display dialog __message buttons {"OK"} default button 1
end printf
end script
This is similar to your other topic, you just need to follow the flow of your script.
In the hangmanGame script’s startGame() handler, you are using the wordGuessed() handler to determine if the word was guessed, so the dialog can go where you are getting that result, for example:
if my wordGuessed() then
display dialog "You guessed the word!!!"
set my score to ((25 * (26 / (length of my usedChars))) as integer)
return true
end if

How to add new features to my Hangman game?

I am working on a game, Hangman. I have the code down, I just want to display the word if you lose. How can I do that?
hangman's init()--by Londres on Stack Overflow
script hangman
property stdin : missing value
property stdout : missing value
property dict : missing value
on init()
--starting up the game
set stdin to parent's hangmanStdin's alloc()'s init()
set stdout to parent's hangmanStdout's alloc()'s init()
set dict to parent's hangmanDictionary's alloc()'s init()
my mainLoop()
end init
on mainLoop()
repeat --endless
set option to stdin's getOptions("Lobby", "What would you like to do?", {"New Game", "Quit"})
if option is "New Game" then
set difficulty to stdin's getOptions("New Game", "Choose your difficulty", {"Normal", "Easy", "Hard"})
--replace this line with an automatic word generator
set x to parent's hangmanGame's alloc()'s initWithWordAndDifficulty(dict's getWord(), difficulty)
if x's startgame() is false then
return
else
stdout's printf("You've scored " & x's score & " points.")
end if
--game is over so clear it
set x to missing value
else
exit repeat
end if
end repeat
end mainLoop
on shouldTerminate()
return true
end shouldTerminate
on alloc()
copy me to x
return x
end alloc
end script
script hangmanGame
property parent : hangman
property wordToGuess : missing value
property maxFaults : missing value
property usedChars : missing value
property faults : missing value
property score : 0
on initWithWordAndDifficulty(theWord, theDifficulty)
if theDifficulty = "Hard" then
set my maxFaults to 5
else if theDifficulty = "Normal" then
set my maxFaults to 8
else --easy or any other value will be handled as easy
set my maxFaults to 12
end if
set my wordToGuess to theWord
set my usedChars to {}
set my faults to 0
set my score to 0
return me
end initWithWordAndDifficulty
on startgame()
repeat --endless
set __prompt to "Faults Left: " & maxFaults - faults & return & "The Word: " & my makeHiddenField()
set c to parent's stdin's getChar(__prompt)
if c = false then
return false
end if
--first check if getChar did give us any result
if length of c is not 0 then
--check if teh character is valid
if c is in "abcdefghijklmnopqrstuvwxyz" then
--check if we already checked this before
if c is not in my usedChars then
set end of my usedChars to c
--check if player guessed wrong character
if c is not in wordToGuess then
set faults to faults + 1
end if
end if
end if
end if
--check if player guessed all characters of word
if my wordGuessed() then
set my score to ((25 * (26 / (length of my usedChars))) as integer)
return true
end if
--check if player reached the max faults he's allowed to make
if my faults = my maxFaults then
return 0
end if
end repeat
end startgame
on wordGuessed()
repeat with aChar in every text item of my wordToGuess
if aChar is not in my usedChars then
return false
end if
end repeat
return true
end wordGuessed
on makeHiddenField()
set characterArray to {}
repeat with aChar in every text item of my wordToGuess
if aChar is in my usedChars then
set end of characterArray to aChar as string
else
set end of characterArray to "_"
end if
end repeat
set AppleScript's text item delimiters to space
set hiddenField to characterArray as string
set AppleScript's text item delimiters to ""
return hiddenField
end makeHiddenField
end script
script hangmanDictionary
property parent : hangman
property wordsPlayed : missing value
property allWords : missing value
on init()
set wordsPlayed to {}
--try to get more words from a file for example
set allWords to {"Hangman", "Police", "Officer", "Desktop", "Pencil", "Window", "Language", "Wealthy", "Trauma", "Spell", "Rival", "Tactical", "Thin", "Salty", "Bluish", "Falcon", "Distilery", "Ballistics", "Fumbling", "Limitless", "South", "Humble", "Foreign", "Affliction", "Retreat", "Agreeable", "Poisoner", "Flirt", "Fearsome", "Deepwater", "Bottom", "Twisted", "Morsel", "Filament", "Winter", "Contempt", "Drimys", "Grease", "Awesome", "Compulsive", "Crayon", "Prayer", "Blonde", "Backbone", "Dreamland", "Ballet", "Continuous", "Aerobatic", "Hideous", "Harmonic", "Lottery", "Encrypt", "Cable", "Aluminium", "Hunter", "National", "Hunter", "Mechanical", "Deadbeat", "Opposition", "Threat", "Decadent", "Gazelle", "Guild", "Authoritive", "Deliverance", "Severe", "Jerid", "Alarm", "Monochrome", "Cyanide", "External", "Potential", "Section", "Innocent", "Drifting", "Amnesia", "Domino", "Flimsy", "Flamethrowing", "Advocate", "Hirsute", "Brother", "Ephemeral", "Brutal", "Decade", "Drauma", "Dilemma", "Exquisite", "Glimmer", "Fugitive", "Digital", "Associate", "Ambivalent", "Ambulatory", "Apology", "Brawler", "Molecular", "Insurance", "Contractual", "Initial", "Calibration", "Heretical", "Disclosure", "Guerilla", "Dismember", "Minimal", "Altercation", "Eastern", "Integrate", "Femur", "Metallic", "Ambition", "Auxiliary", "Esoteric", "Converse", "Accepting", "Juvenile", "Efficacious", "Complex", "Imperil", "Division", "Onerous", "Astonish", "Scandalous", "Quaint", "Dominate", "Contrary", "Conspiracy", "Earthquake", "Embarrassment", "Exclude", "Ambiguous", "Captivate", "Compliance", "Migration", "Embryo", "Abandon", "Conservation", "Appreciate", "Applaud", "Pension", "Voyage", "Influence", "Consensus", "Incapable", "Economy", "Parameter", "Contrast", "Sensitive", "Meadow", "Chimney", "Familiar", "Serious", "Credibility", "Infrastructure", "Museum", "Relinquish", "Merit", "Coalition", "Retirement", "Transaction", "Official", "Composer", "Magnitude", "Committee", "Privilege", "Diamond", "Obligation", "Transition", "Jockey", "Reinforce", "Conflict", "Offensive", "Detective", "Effective", "Detector"}
return me
end init
on getWord()
set randomNr to (random number from 1 to (length of (my allWords))) as integer
--you could do somethinh here when a word is used again
return item randomNr of my allWords as string
end getWord
end script
script hangmanStdin
property parent : hangman
on init()
return me
end init
on getChar(__prompt)
set x to display dialog __prompt buttons {"Go", "Quit"} default button "Go" default answer ""
if button returned of x = "Quit" then
return false
end if
if length of x's text returned = 0 then
return ""
end if
return character 1 of x's text returned
end getChar
on getOptions(__title, __message, __options)
return button returned of (display alert __title message __message buttons __options default button 1)
end getOptions
end script
script hangmanStdout
property parent : hangman
on init()
return me
end init
on printf(__message)
display dialog __message buttons {"OK"} default button 1
end printf
end script
How can I make it so if you lose the game, not only does it say the you got 0 points but also say the word that they missed. I'm trying my best to get this done. It's a project that I'm doing to get the basics of coding. Took me awhile.
You are only checking the return result from hangmanGame’s startGame() handler for false or otherwise, but the handler returns 0 if all the faults are used. You could add an additional check in there, but the easiest way would probably be to add a dialog in the startGame() comparison, for example:
if my faults = my maxFaults then
display dialog "The word was " & quoted form of wordToGuess
return 0
end if

Bracket finding algorithm lua?

I'm making a JSON parser and I am looking for an algorithm that can find all of the matching brackets ([]) and braces ({}) and put them into a table with the positions of the pair.
Examples of returned values:
table[x][firstPos][secondPos] = type
table[x] = {firstPos, secondPos, bracketType}
EDIT: Let parse() be the function that returns the bracket pairs. Let table be the value returned by the parse() function. Let codeString be the string containing the brackets that I want to detect. Let firstPos be the position of the first bracket in the Nth pair of brackets. Let secondPos be the position of the second bracket in the Nth pair of brackets. Let bracketType be the type of the bracket pair ("bracket" or "brace").
Example:
If you called:
table = parse(codeString)
table[N][firstPos][secondPos] would be equal to type.
Well, In plain Lua, you could do something like this, also taking into account nested brackets:
function bm(s)
local res ={}
if not s:match('%[') then
return s
end
for k in s:gmatch('%b[]') do
res[#res+1] = bm(k:sub(2,-2))
end
return res
end
Of course you can generalize this easy enough to braces, parentheses, whatever (do keep in mind the necessary escaping of [] in patterns , except behind the %b pattern).
If you're not restricted to plain Lua, you could use LPeg for more flexibility
If you are not looking for the contents of the brackets, but the locations, the recursive approach is harder to implement, since you should keep track of where you are. Easier is just walking through the string and match them while going:
function bm(s,i)
local res={}
res.par=res -- Root
local lev = 0
for loc=1,#s do
if s:sub(loc,loc) == '[' then
lev = lev+1
local t={par=res,start=loc,lev=lev} -- keep track of the parent
res[#res+1] = t -- Add to the parent
res = t -- make this the current working table
print('[',lev,loc)
elseif s:sub(loc,loc) == ']' then
lev = lev-1
if lev<0 then error('too many ]') end -- more closing than opening.
print(']',lev,loc)
res.stop=loc -- save bracket closing position
res = res.par -- revert to the parent.
end
end
return res
end
Now that you have all matched brackets, you can loop through the table, extracting all locations.
I figured out my own algorithm.
function string:findAll(query)
local firstSub = 1
local lastSub = #query
local result = {}
while lastSub <= #self do
if self:sub(firstSub, lastSub) == query then
result[#result + 1] = firstSub
end
firstSub = firstSub + 1
lastSub = lastSub + 1
end
return result
end
function string:findPair(openPos, openChar, closeChar)
local counter = 1
local closePos = openPos
while closePos <= #self do
closePos = closePos + 1
if self:sub(closePos, closePos) == openChar then
counter = counter + 1
elseif self:sub(closePos, closePos) == closeChar then
counter = counter - 1
end
if counter == 0 then
return closePos
end
end
return -1
end
function string:findBrackets(bracketType)
local openBracket = ""
local closeBracket = ""
local openBrackets = {}
local result = {}
if bracketType == "[]" then
openBracket = "["
closeBracket = "]"
elseif bracketType == "{}" then
openBracket = "{"
closeBracket = "}"
elseif bracketType == "()" then
openBracket = "("
closeBracket = ")"
elseif bracketType == "<>" then
openBracket = "<"
closeBracket = ">"
else
error("IllegalArgumentException: Invalid or unrecognized bracket type "..bracketType.."\nFunction: findBrackets()")
end
local openBrackets = self:findAll(openBracket)
if not openBrackets[1] then
return {}
end
for i, j in pairs(openBrackets) do
result[#result + 1] = {j, self:findPair(j, openBracket, closeBracket)}
end
return result
end
Will output:
5 14
6 13
7 12
8 11
9 10

How to Winwait for two windows simultaneously in AutoIt?

I would like to know if its possible to WinWaitActive for WindowWithThisTitle and WindowWithThatTitle at the same time. I'm executing a command and there could be a window telling me that the connection failed or a user/pass dialog coming up.
Is there another way doing it as this?
WinWaitActive("Title1", "", 5)
If(WinExists("Title1")) Then
MsgBox(0, "", "Do something")
Else
If(WinExists("Title2")) Then
MsgBox(0, "", "Do something else")
EndIf
EndIf
Because I don't want to have the timeout which could be more than 15 seconds.
A simpler solution might be to use a REGEX title in your WinWaitActive as defined here
You would then have something like this:
$hWnd = WinWaitActive("[REGEXPTITLE:(WindowWithThisTitle|WindowWithThatTitle)]")
If WinGetTitle($hWnd) = "WindowWithThisTitle" then
DoSomething()
Else
DoSomethingElse()
EndIf
How about something like this.
$stillLooking = True
While $stillLooking
$activeWindowTitle = WinGetTitle(WinActive(""))
If $activeWindowTitle == "Title1" Then
MsgBox(0, "", "Do something")
$stillLooking = False
ElseIf $activeWindowTitle == "Title2" Then
MsgBox(0, "", "Do something else")
$stillLooking = False
EndIf
sleep(5)
WEnd
Because I don't want to have the
timeout which could be more than 15
seconds.
WinWaitActive() doesn't have a timeout unless you specify one. You gave it a five second timeout but you could leave that off and it would wait forever.
You can use this Functions for two windows ..
; #FUNCTION# ====================================================================================================================
; Name...........: _2WinWait
; Description ...: Wait For Tow Windows .
; Syntax.........: _2WinWait ($FirstTitle,$SecondTitle,[$FirstText = "" ,[$SecondText = ""]] )
; Parameters ....: $FirstTitle - Title Of First Wondow
; $SecondTitle - Title Of Second Wondow
; $FirstText - Text Of First Wondow
; $SecondText - Text Of Second Wondow
; Return values .: Success - None
; Failure - Returns a 0 => If Your Titles Is Wrong
; Author ........: Ashalshaikh : Ahmad Alshaikh
; Remarks .......:
; Related .......:
; Link ..........;
; Example .......; No
; ===============================================================================================================================
Func _2WinWait ($FirstTitle,$SecondTitle,$FirstText = "" ,$SecondText = "" )
If $FirstTitle = "" Or $SecondTitle = "" Then
Return 0
Else
Do
Until WinExists ($FirstTitle,$FirstText) Or WinExists ($SecondTitle,$SecondText)
EndIf
EndFunc
; #FUNCTION# ====================================================================================================================
; Name...........: _2WinWait_Any
; Description ...: Wait For Tow Windows And Return Any Window Id Exists .
; Syntax.........: _2WinWait_Any ($FirstTitle,$SecondTitle,[$FirstText = "" ,[$SecondText = ""]] )
; Parameters ....: $FirstTitle - Title Of First Wondow
; $SecondTitle - Title Of Second Wondow
; $FirstText - Text Of First Wondow
; $SecondText - Text Of Second Wondow
; Return values .: Success - Number Of Window ==> 1= First Window , 2= Second Window
; Failure - Returns a 0 => If Your Titles Is Wrong
; Author ........: Ashalshaikh : Ahmad Alshaikh
; Remarks .......:
; Related .......:
; Link ..........;
; Example .......; No
; ===============================================================================================================================
Func _2WinWait_Any ($FirstTitle,$SecondTitle,$FirstText = "" ,$SecondText = "" )
If $FirstTitle = "" Or $SecondTitle = "" Then
Return 0
Else
Do
Until WinExists ($FirstTitle,$FirstText) Or WinExists ($SecondTitle,$SecondText)
If WinExists ($FirstTitle,$FirstTexit) Then
Return 1
Else
Return 2
EndIf
EndIf
EndFunc
for more with examples
I'm fairly new to autoit and the programming world in general and I had this same dilemma. Luckily I figured out a straight fwd way to do it:
Do
$var1 = 0
If WinGetState("Document Reference","") Then
$var1 = 1
ElseIf WinGetState("Customer Search","") Then
$var1 = 1
EndIf
Until $var1 = 1
So it'll stay in the loop until it finds the window and sets $var1 to 1. There's probably easier ways (I'm sure developers are gasping at this) but this is straight fwd enough for me.
You can create an infinite while loop with if statements in there:
#include <MsgBoxConstants.au3>
Example()
Func Example()
While 1
; Test if the window exists and display the results.
If WinExists("Windows Security") Then
Local $hWnd = WinWaitActive("Windows Security", "", 2000)
ControlSetText($hWnd, "", "[CLASS:Edit; INSTANCE:1]", "hel233")
ControlClick("Windows Security","","[CLASS:Button; INSTANCE:2]")
Sleep(5000)
EndIf
; Test if the window exists and display the results.
If WinExists("Spread the Word") Then
'The line below will wait until the window is active, but we don't need that
'Local $hWnd = WinWaitActive("Spread the Word", "", 2000)
WinClose("Spread the Word")
Sleep(5000)
EndIf
wend
EndFunc

Resources