Jump to content
Sign in to follow this  
gcue

cancel a function run?

Recommended Posts

gcue

is there a way to cancel a function while its running? is there an easy way to do this? i would think you cant in autoit due to the inability to run multi-threads.. right? ^_^

Share this post


Link to post
Share on other sites
weaponx

Return

Share this post


Link to post
Share on other sites
gcue

so on an active process, a button is selectable? (with return as function behind it)

Share this post


Link to post
Share on other sites
Melba23

gcue,

You could do this by using a HotKey to set a flag and then polling the flag in the function. Here is some proof-of-concept code:

Global $fFlag = False

HotKeySet("{ESC}", "Set_Flag")

my_func()
ConsoleWrite("Out" & @CRLF)

Func my_func()
    ConsoleWrite("In" & @CRLF & $fFlag & @CRLF)
    While 1
        If $fFlag Then Return
    Sleep(10)
    WEnd

EndFunc

Func Set_Flag()
    $fFlag = True
    ConsoleWrite($fFlag & @CRLF)
EndFunc

Of course, it is only useable if the function you wish to interrupt has suitable breaks to insert the If $fFlag lines, or has a nice useful loop in it. :-)

I do not believe you can do it with a button, because the function called by the button will be queued until the running function ends - which is of no use. :-(

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites
gcue

that works well in a loop but what about other functions?

prob no way huh?

Share this post


Link to post
Share on other sites
Skruge

is there a way to cancel a function while its running? is there an easy way to do this? i would think you cant in autoit due to the inability to run multi-threads.. right? ^_^

You can't do multiple threads, but you can do multiple processes, which would work for your situation.

Script calls itself with a switch, new process runs your function, hotkey or other method kills the child process on demand.


[font="Tahoma"]"Tougher than the toughies and smarter than the smarties"[/font]

Share this post


Link to post
Share on other sites
gcue

anyone have an example?

Share this post


Link to post
Share on other sites
guinness

gcue,

This thread is over 2 years old, surely you would've learnt something by now. Melba gave you an example, I suggest you try that.


UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Share this post


Link to post
Share on other sites
Melba23

gcue,

This is the Interrupting a running function tutorial that I added to the Wiki since this thread was started. It should help you break into your function - it offers several ways to do it. :)

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites
gcue

very interesting.. too bad only doable through hotkey =/ (when using onevent)

thanks for creating the wikki entry melba =)

Share this post


Link to post
Share on other sites
Melba23

gcue,

too bad only doable through hotkey(when using onevent)

You obviously did not read the tutorial very thoroughly - it shows multiple ways to interrupt a function in both OnEvent and MessageLoop modes. ;)

If you cannot be bothered to read a tutorial which explains in detail how to use these different methods and shows examples of how to code them, why should we help you any further? :)

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites
gcue

ahh sorry i misread it.. i thought the examples was a progression of the same example for each messageloop and onevent =)

definitely makes sense now - ill try it out

thanks!!

Share this post


Link to post
Share on other sites
Melba23

gcue,

Please ask if you run into diffculties. :)

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites
gcue

got it working on thanks again for the tutorial.

the problem im coming across is that i have over 100 functions - my while loop is going to need that many if then or case statements along with that im gonna need that many extra variables.. *sigh*

maybe theres a more code efficient way?

#include <GUIConstantsEx.au3>

; Declare a flag
Global $fRunOne = False
Global $fRunTwo = False

Opt("GUIOnEventMode", 1)

$hGUI = GUICreate("Test", 500, 500)
GUISetOnEvent($GUI_EVENT_CLOSE, "_Exit")

$cancel_button = GUICtrlCreateButton("CANCEL", 5, 5, 50, 20)
GUICtrlSetOnEvent(-1, "CANCEL_FUNCS")

$hButton_1 = GUICtrlCreateButton("Func One", 10, 50, 80, 30)
GUICtrlSetOnEvent($hButton_1, "_Func_1")
$hButton_2 = GUICtrlCreateButton("Func Two", 10, 90, 80, 30)
GUICtrlSetOnEvent($hButton_2, "_Func_2")

GUISetState()

While 1
    Sleep(10)
    ; Check if the flag has been set by the OnEvent function
    Select
        Case $fRunOne = True
        _Func_1_Run()
        Case $fRunTwo = True
        _Func_2_Run()
    EndSelect
WEnd

Func _Func_1()
    ; Set the flag within the OnEvent function
    $fRunOne = True
EndFunc   ;==>_Func_1

Func _Func_1_Run()
    For $i = 1 To 2000
        ConsoleWrite($i & "-Func 1 Running" & @CRLF)
        Sleep(100)
        if $fRunOne = False Then
            ExitLoop
        EndIf
    Next
EndFunc   ;==>_Func_1_Run

Func _Func_2()
    ; Set the flag within the OnEvent function
    $fRunTwo = True
EndFunc   ;==>_Func_1

Func _Func_2_Run()
    For $i = 1 To 2000
        ConsoleWrite($i & "-Func 2 Running" & @CRLF)
        Sleep(100)
        if $fRunTwo = False Then
            ExitLoop
        EndIf
    Next
EndFunc   ;==>_Func_2

Func CANCEL_FUNCS()
    ConsoleWrite("CANCELED" & @CRLF)
    $fRunOne = False
    $fRunTwo = False
EndFunc

Func _Exit()
    Exit
EndFunc   ;==>_Exit

Share this post


Link to post
Share on other sites
Melba23

gcue,

The first question to ask is if you will need to interrupt all of the functions? Many of the functions in my scripts are simple helper functions which complete very quickly - only a few tend to last long enough to cause a serious delay in script response.

The second point is that you have chosen the "simple" way to interrupt in OnEvent mode - which has the disadvantage of needing you to poll the flags in the While...WEnd loop. Lower down in the tutorial is another OnEvent script which shows you how to interrupt functions directly - with either a HotKey, an Accelerator key or a control. If you were to use one of those methods then your problem vanishes entirely. ;)

Let me know if you need any more advice - always happy to help out. :)

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites
gcue

yes will need to interrupt most of them unfortunately.

yea i saw the hotkey way - sometimes thats hard to communicate as a way of canceling - i have a large user base that uses the tool - i can try to put the note "KEY to cancel" in a noticeable place and see how that goes =)

thanks again for the awesome wiki entry.

your help is VERY much appreciated here Melba!

Edited by gcue

Share this post


Link to post
Share on other sites
gcue

hey Melba,

So I went with the hotkey method works great! thanks again for your help. Only Problem is that the hotkey applies even when my gui isnt being selected so it might conflict with another program. Sure I can set something like CTRL+ATL+SHIFT+P which probably won't get used by anything else. however hard to remember weird combination of keys like that. I am trying to use it to cancel a running process so ESC would be ideal but then ESC wont work in other programs.

ive also tried setting the hotkey through GUISetAccelerators but that wont interrupt a running process.

any ideas?

thanks in advance

Share this post


Link to post
Share on other sites
Melba23

gcue,

ive also tried setting the hotkey through GUISetAccelerators but that wont interrupt a running process

Yes it will - go and read the tutorial again. :oops:

M23


Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind._______My UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

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
Sign in to follow this  

×