Jump to content
TheOnlyOne

Hotkeyset seems to stop working when i hit a while loop

Recommended Posts

So currently I have some code waiting for a status to change(there is different indicators to check if this status has changed) 

Func oneRow($count)
    $globaltimer = _Timer_SetTimer($gui, 60000*10, "reset")
    $errTimer = TimerInit()
While (1)
        If PixelGetColor(1117, 326) = 0xC6C6C6 Then ExitLoop (1)
        Sleep(500)
        MouseClick("right")
        Sleep(600)
        If PixelGetColor(1117, 326) = 0xC6C6C6 Then ExitLoop (1)

        If TimerDiff($errTimer) > 5000 Then
            If PixelGetColor(1100, 310) = 0x707070 Or PixelGetColor(901, 305) = 0xE0E0E0 Or PixelGetColor(1043, 383) = 0xC6C6C6 Then
                Sleep(100)
                Send("{esc}")
                Sleep(1000)

            EndIf
        EndIf
    WEnd



....



EndFunc   ;==>oneRow

The two timers is for error checking. This works just fine the problem comes when I go into the while 1 loop, my hotkeys at the top of the program seems to stop working, for an example 

HotKeySet("{f1}", "stop")

Func stop()
    Exit
EndFunc   ;==>stop

Does not work at all after the while loop. The globaltimer is never called even though i tried setting the delay all the way down to 3 seconds. So I thought that maybe one of the function I use is blocking so the timer would never be called/the hotkey wouldn't work? if i make an delay just before the while loop the hotkey works just fine. Oh and the errTimer is supossed to not reset after 5 seconds but should keep making the check it does if five seconds have passed

Edited by TheOnlyOne
words are hard

Share this post


Link to post
Share on other sites

Can't reproduce, your code is not testable for anyone else, the rest of your code and/or the application that you're trying to work with and/or pretty much anything else may throw sand in the machine.

I tried to write a small reproducer that uses both types of timers at the same time as well and a hotkey, works fine for me:

#include <Timers.au3>

HotKeySet("x", "exiter")

doThing()
Exit

Func doThing()
    $globaltimer = _Timer_SetTimer(-1, 10000, "doBeep")
    $beepTimer = TimerInit()
    While (1)
        If TimerDiff($beepTimer) > 6000 and TimerDiff($beepTimer) < 8000 Then
            Beep(2000, 300)
        EndIf
    WEnd
EndFunc   ;==>doThing

Func doBeep()
    Beep(1000, 300)
    Sleep(100)
EndFunc   ;==>doBeep

Func exiter()
    Exit
EndFunc   ;==>exiter

Can you try and reproduce your issue with a standalone reproducer script?


Roses are FF0000, violets are 0000FF... All my base are belong to you.

Share this post


Link to post
Share on other sites

Your script snipets should work, if the scipt is correctly completed, so post whole runable (reproducer) sdcript, showing your issue. But maybe another skript capures the F1-key?

Quote

If two AutoIt scripts set the same hotkeys, you should avoid running those scripts simultaneously as the second script cannot capture the hotkey unless the first script terminates or unregisters the key prior to the second script setting the hotkey.

 

Share this post


Link to post
Share on other sites

Hmm not sure I can do that, I see that your example is working for me too. 

I have this code calling my function 

$return = 0
    For $i = 0 To 5
        If $pause = True Then
            pause()
        EndIf
        MsgBox(0,"","before one row")
        $return = oneRow($i)
        MsgBox(0,"",$return)
        If $return = 232 Then Return 232
        Sleep($waitDelay)
    Next

the msgboxes is something i inserted for debugging purposes. I also tried to add MsgBox(0,"","first") to the top of the oneRow function. So when i run the code it runs as expected the first time, shows "before one row" messagebox and afterwards the "first" msgbox. Then after 5 seconds it actually shows the  "before one row" msgbox again so it must have passed one of my pixelgetcolor calls(even though the status isnt correct yet). So i tried adding this to the if block that passes

If PixelGetColor(1100, 310) = 0x707070 Or PixelGetColor(901, 305) = 0xE0E0E0 Or PixelGetColor(1043, 383) = 0xC6C6C6 Then
                MsgBox(0,"","sucess " & @crlf & hex(PixelGetColor(1100, 310)) & @crlf & hex(PixelGetColor(901, 305)) & @crlf & hex(PixelGetColor(1043, 383)))
                Sleep(100)
                Send("{esc}")
                Sleep(1000)

            EndIf

But the msgbox is never shown. If i add an empty msgbox it is shown. I tried without the hex call but with the same result, is the pixegetcolor function returning errors maybe, i have never seen that before?

Another weird thing is after it shows the "before one row" msgbox the second time it doesnt show the next msgbox at the top of oneRow function ? As you said my code is properly to messy atm. I would have a hard time making a reproducable example which is not very good..

Edited by TheOnlyOne
removed duplicate code tags

Share this post


Link to post
Share on other sites

I'm not saying whether or not your code is messy, and even messy code should still work if it is actually correct (just harder to work with :)).

If you want to know how far your code gets during execution, there are a few shortcuts you could take to get some information, such as enabling the TrayIconDebug option or using Tools -> Trace: add trace lines in Scite. You can always add your own ConsoleWrite commands to show more debug information, such as results, errors and extended error information returned from function calls. (Much more useful than MsgBox'es IMHO as they don't require interaction, don't overlap any gui etc..)

I personally cannot see anything intrinsically wrong with this code (maybe someone else can?), but without clear information on when what happens exactly, it's blindfolded troubleshooting, at least to me. But that's what reproducers are for. The thing with reproducers is that if you feel like you would have a hard time making one, it's probably a sign that you have to rethink your solution to begin with, otherwise it's just trial-and-error to find a working band-aid...


Roses are FF0000, violets are 0000FF... All my base are belong to you.

Share this post


Link to post
Share on other sites

I'm not sure but I think "Sleep" is a blocking function.
The help file tells us: "If the current function is a "blocking" function, then the key-presses are buffered and execute as soon as the blocking function completes."


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2019-08-19 - Version 1.4.13.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2019-07-24 - Version 1.3.6.0) - Download - General Help & Support - Example Scripts - Wiki
Outlook Tools (NEW 2019-07-22 - Version 0.6.0.0) - Download - General Help & Support - Wiki
ExcelChart (2017-07-21 - Version 0.4.0.1) - Download - General Help & Support - Example Scripts
PowerPoint (2017-06-06 - Version 0.0.5.0) - Download - General Help & Support
Excel - Example Scripts - Wiki
Word - Wiki
 
Tutorials:

ADO - Wiki

 

Share this post


Link to post
Share on other sites

HotKeySet functionality remains active and also works immediately during a sleep.

/edit Tested with:

HotKeySet("x", "quitter")

Beep(1000, 200)
sleep(20000)

Func quitter()
    Beep(1500, 200)
    Exit
EndFunc   ;==>quitter

 

Edited by SadBunny

Roses are FF0000, violets are 0000FF... All my base are belong to you.

Share this post


Link to post
Share on other sites

Yea I might have to rethink the solution.. just annoys me because I feel like it should work. I just tried to add a tooltip to the while loop in oneRow() with the timerdiff inside. So the hotkey apperently works until 30-40 seconds have passed ?? there is no other code being executed other than the code inside the loop ..

Edited by TheOnlyOne

Share this post


Link to post
Share on other sites

Show me a simple reproducer of your script which actually works and we can check as to why you are seeing this.

Jos

Share this post


Link to post
Share on other sites

Okay I might have found the problem with why the hotkeyset didn't work. I took another look at your first example @SadBunny and saw you used -1 for the hwnd. I thought you had to give it a GUI reference so i had created one like this, with the timer referencing it as shown earlier:

$gui = GUICreate("", 0, 0)

$globaltimer = _Timer_SetTimer($gui, Random(6000 * 2, 6000 * 5, 1), "reset")

I tried changing $gui to -1 and now the hotkey works even after 60+ seconds why is that? The function reset does not seem to be called though ? Tried chaning it to 10 seconds instead of a random generated number but with the same result?

Func reset()
    _Timer_KillTimer($gui, $globaltimer)
    MsgBox(0, "", "in reset")
    ...
EndFunc   ;==>reset

the callback function never seems to be called in your example nether

Edited by TheOnlyOne

Share this post


Link to post
Share on other sites

True, and I didn't want/need it to, I just wanted it to exist. Now that you mention it, the result of that _Timer_SetTimer returns 0 so the timer call fails and my test is faulty. That means that in your new case, the timer probably isn't created either and now your hotkey now remains working. So the problem still looks to be with that combination, or some contingency combined with that combination.

Finding out which one of those two is the case is a matter of elimination :) Either start from scratch with that combination and see if you can reproduce, or snip away every other contingency until you arrive at the last contingency that determines whether this problem occurs or not, and you can write a reproducer (and/or find your error :) ).


Roses are FF0000, violets are 0000FF... All my base are belong to you.

Share this post


Link to post
Share on other sites

So here the timer actually works :) Maybe this is better to play around with?

#include <Timers.au3>

HotKeySet("x", "exiter")

Global $gui = GUICreate("hello", 300, 300, 100, 100)
;~ GUISetState(@SW_SHOW, $gui)

doThing()
Exit

Func doThing()
    Local $globaltimer = _Timer_SetTimer($gui, 6000, "doTimerFunction")
    ConsoleWrite("Timer id: " & $globaltimer & @CRLF)
    $beepTimer = TimerInit()
    While (1)
        If TimerDiff($beepTimer) > 3000 And TimerDiff($beepTimer) < 4000 Then
            Beep(1500, 100)
        EndIf
    WEnd
    Sleep(10000)
EndFunc   ;==>doThing

Func doTimerFunction($hWnd, $iMsg, $iIDtimer, $iTime)
    Beep(1000, 300)
EndFunc   ;==>doBeep

Func exiter()
    Exit
EndFunc   ;==>exiter

 


Roses are FF0000, violets are 0000FF... All my base are belong to you.

Share this post


Link to post
Share on other sites

Oh god i feel so stupid ..  my reset function didn't have any parameters.. Well thanks for your help, would properly been stuck with this for atleast a few hours more without it. 

Share this post


Link to post
Share on other sites

See, this is why reproducers are so important :) 9 out of 10 times (if not more) even the process of trying to come up with a reproducer from scratch, or stripping your code down until the problem disappears and then looking at the last thing you stripped, shows the actual problem.

Well, glad I could help :cheer:


Roses are FF0000, violets are 0000FF... All my base are belong to you.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • By ThePoro
      Hi everyone.
      I want to ask about this : 
      I want it runs from 1 to 100 and It opens 10 firefox profiles then access youtube. After I close a firefox window, the loop runs and wait for another window close until loop ends
      I have a loop like this.
      Func launch() Local $from = Int(GUICtrlRead($input1)) Local $to = Int(GUICtrlRead($input2)) If $to <> "" Then While $from <= $to Local $profile = $to _RunDos("start firefox.exe -p " & $profile & " -no-remote youtube.com") $to=$to+1 WEnd Else Local $profile = $to _RunDos("start firefox.exe -p " & $profile & " -no-remote youtube.com") EndIf EndFunc Is there any solution?
      Thank you!
    • By Rhidlor
      First off, the project I'm working on revolves around AS/400 "Client Access software", it's foundation is directly influenced by the thread linked at the bottom of this post. Moving on, to explain the problem I'm facing; my project utilizes an infinite While loop and automatically performs semi-hard coded monotonous tasks to save users time and effort, the problem is, occasionally and unexpectedly "Display Messages" will popup and the core script will continue executing instead of dismissing said message and the script "breaks". As a countermeasure I've added some code to the While loop in an effort to intervene and dismiss these display messages before the core script has a chance to do anything... however it doesn't work. I hope I didn't do too bad of a job explaining that. 
      So I think my question is: How can I temporarily "pause" the core script when these messages spontaneously appear?
      The only other solution I thought of would be to check if a display message has appeared before executing every line of code but that obviously isn't very practical.
      Any and all help is greatly appreciated!
      Thanks
       
      ;Loop to keep script running and handle display messages While 1 dismiss_display_messages() Sleep(50) WEnd ;Function to dismiss display messages Func dismiss_display_messages() If $ps.SearchText("Display Messages") Then $ps.SendKeys("[enter]", 8, 1) ;This while loop waits until the display message has disappeared to resume the core script While $ps.SearchText("Display Messages") Sleep(100) WEnd EndIf EndFunc  
       
    • By UGH
      Autoit team are assbags.    They want to hold out that they are soooo much smarter than everyone else and they really don't want to help anyone with their questions.   In that case then why have a website.   Oh i know, they get their kicks out of laughing at everyone. 
       
       
       
       
       
       
       
    • By XinYoung
      Hello all,
      Preface: Column A is full of courses. Column B is full of usernames. If course (A1) exists, we check to see if username (B1) is enrolled. If user is found, the user is un-enrolled. Then Loop.
      I am working on a script that loops through an Excel file and pastes the content from A1 into a textbox in IE, does some stuff, then pastes the content from B1 into a different textbox. Then it loops around until all used rows in columns A and B have been accounted for.
      For some reason, column A loops properly but column B doesn't. B1 is pasted over and over again. So, as it loops, B1 is constantly being pasted, first accompanying A1's loop, then A2, and so on.
      The OpenExcel() func opens the Excel file the user specifies in an earlier function. It's supposed to gather the entire used range of columns A and B. The SearchCourse() func only uses column A, pasting its content into a Search tool in IE. This seems to be working fine. SearchResult() puts "Course Not Found" into column C if the search fails. If the search is successful, however, we move onto... EnterCourse(). This simply gets us to the place where column B's content comes into play. UnenrollNow(). Here, we paste the variable $_userName into a textbox. I don't know why it's always B1  Func OpenExcel() If Not WinExists($hWnd) Then MsgBox(16, "Window closed", "The Internet Explorer window was closed. Please start over.") _Exit() Else $oExcel = _Excel_Open() Global $oWorkbook = _Excel_BookOpen($oExcel, $ChosenFileName, Default, True, True) $oExcel.Sheets("CopyCourses").Activate ;~ Get all used cells in columns A and B $aSearchItems = _Excel_RangeRead($oWorkbook, 1, $oWorkbook.Sheets("CopyCourses").Usedrange.Columns("A:B")) ;~ Create the $aSearchResult array ReDim $aSearchResult[UBound($aSearchItems)] ;~ Loop through the array starting at 0 until the end of the array which is (Ubound($aSearchItems) - 1) For $i = 0 To UBound($aSearchItems) - 1 ;~ Column 0 ConsoleWrite($aSearchItems[$i][0] & @CRLF) ;~ Column 1 ConsoleWrite($aSearchItems[$i][1] & @CRLF) $aSearchResult[$i] = SearchCourse($aSearchItems[$i][0], $aSearchItems[$i][1]) Next _Excel_RangeWrite($oWorkbook, Default, $aSearchResult, "C1") ;~ When the loop is complete, run the Finished function. Finished() EndIf EndFunc ;==>OpenExcel Func SearchCourse($_sSearchResult, $_userName) If Not WinExists($hWnd) Then MsgBox(16, "Window closed", "The Internet Explorer window was closed. Please start over.") _Exit() Else _IENavigate($oIE, $urlBBCourseSearch) _IELoadWait($oIE) Local $oForm = _IEGetObjByName($oIE, "courseManagerFormSearch") Local $oSearchString = _IEFormElementGetObjByName($oForm, "courseInfoSearchText") _IEFormElementSetValue($oSearchString, $_sSearchResult) _IEFormSubmit($oForm) _IELoadWait($oIE) Local $oBBTable = _IETableGetCollection($oIE, 2) $aBBTableData = _IETableWriteToArray($oBBTable) Return SearchResult() EndIf EndFunc ;==>SearchCourse Func SearchResult() If Not WinExists($hWnd) Then MsgBox(16, "Window closed", "The Internet Explorer window was closed. Please start over.") _Exit() Else Local $sResult $iSearchIndex = _ArraySearch($aBBTableData, "Course ID", 0, 0, 0, 1, 1, 0) If $iSearchIndex = -1 Then $sResult = "Course Not Found" _Excel_RangeWrite($oWorkbook, Default, $aSearchResult, "C1") Else EnterCourse() $sResult = "UnEnrolled!" _Excel_RangeWrite($oWorkbook, Default, $aSearchResult, "C1") EndIf Return $sResult EndIf EndFunc ;==>SearchResult Func EnterCourse() If Not WinExists($hWnd) Then MsgBox(16, "Window closed", "The Internet Explorer window was closed. Please start over.") _Exit() Else Local $clickFail = "DATE CREATED" _IELinkClickByIndex($oIE, 34) _IELoadWait($oIE) $sourceCode = _IEBodyReadHTML($oIE) If StringInStr($sourceCode, $clickFail) <> 0 Then _IELinkClickByIndex($oIE, 35) _IELoadWait($oIE) EndIf $oLink = _IEGetObjById($oIE, "controlpanel.users.and.groups_groupExpanderLink") _IEAction($oLink, "click") Sleep(500) _IELinkClickByText($oIE, "Users") _IELoadWait($oIE) $aSearchResult[$i] = UnenrollNow($aSearchItems[$i][0], $aSearchItems[$i][1]) EndIf EndFunc ;==>EnterCourse Func UnenrollNow($_sourceCourseId, $_userName) If Not WinExists($hWnd) Then MsgBox(16, "Window closed", "The Internet Explorer window was closed. Please start over.") _Exit() Else Local $UserError = "No users found" Local $sResult $criteriaUsername = _IEGetObjById($oIE, "userInfoSearchKeyString") _IEFormElementOptionSelect($criteriaUsername, 0, 1, 'byIndex') $criteriaUsername = _IEGetObjById($oIE, "userInfoSearchOperatorString") _IEFormElementOptionSelect($criteriaUsername, 0, 1, 'byIndex') ;Paste whats copied from column B into the Username text box. Local $oForm = _IEGetObjByName($oIE, "userManagerSearchForm") Local $oSearchString = _IEFormElementGetObjByName($oForm, "userInfoSearchText") ;PROBLEM HERE... _IEFormElementSetValue($oSearchString, $_userName) ;^^^^^^ WHY IS $_userName ALWAYS B1 ??? Sleep(1000) _IEFormSubmit($oForm) _IELoadWait($oIE) $sourceCode = _IEBodyReadHTML($oIE) If StringInStr($sourceCode, $UserError) <> 0 Then $sResult = "User Not Found" _Excel_RangeWrite($oWorkbook, Default, $aSearchResult, "C1") Return $sResult Else MsgBox(0, "Unenrollment READY!", "We're ready to unenroll foreal") $sResult = "DUN" _Excel_RangeWrite($oWorkbook, Default, $aSearchResult, "C1") Return $sResult EndIf EndIf EndFunc ;==>UnenrollNow Please let me know if any further information is needed.
      If you see other problems or redundancies in my code, please let me know.
      Thank you!
       
×
×
  • Create New...