Sign in to follow this  
Followers 0
telmob

Merge two 'while'

35 posts in this topic

#1 ·  Posted (edited)

Hello.

I'm trying to use an example i found here on the forum, with my script, but i'm lost at using two 'While'.

Basically, what i want to know is...

How can i put this:

while 1 ; Main Loop
$slct+=1
sleep(1000)
; AdminFlag() Only needed if using PID-based titling
if $slct>10 then
; auto mappings update:
$slct=0
if $pwdCountdown>0 then $pwdCountdown=$pwdCountdown-1
if $status=0 then
if $unlockTimeout>0 then $mlct+=1
else
$mlct=0
endif
AddMappings()

if $mlct>0 then
$unlockRemTime=$unlockTimeout-$mlct
if $mlct>$unlockTimeout then
$mlct=0
TrayTip("SRP Enforcer","Unlock time-limit reached. Re-applying policy",5,1)
RegWrite($hklm & "SOFTWAREPoliciesMicrosoftWindowsSaferCodeIdentifiers","DefaultLevel","REG_DWORD",0)
if $limitedApps=1 then
SetIFE()
endif
TraySetToolTip("SRP Active")
else
TraySetToolTip("Policy Suspended, " & $unlockRemTime & " minutes remaining")
endif
endif
endif

sleep(1000)
$status=Status()
if $status <> $prevstatus then
$prevstatus=$status
select
case $status = 0
TraySetToolTip("System Unlocked!")
TraySetIcon(@scriptfullpath,-5)
case $status= 1
TraySetIcon()
traysetstate(16)
TraySetToolTip("SRP Active")
case $status= -1
TraySetIcon(@scriptfullpath,-5)
TraySetToolTip("SRP Enforcer Not Installed")
endselect
EndIf
wend ;

Here:

While 1
Switch GUIGetMsg()
Case $GUI_EVENT_CLOSE
GUISetState(@SW_HIDE)
UpdateTray()
Case $MenuMinimize
GUISetState(@SW_HIDE)
UpdateTray()
Case $MenuQuit
Local $LockedModeOnOFF
If Iniread($inifile, "General", "Locked", "")=1 Then $LockedModeOnOFF="LOCKED." & @crlf & "No authorized application will run or install."
If Iniread($inifile, "General", "Locked", "")=0 Then $LockedModeOnOFF="UNLOCKED." & @crlf & "Applications or malware can run and be installed in your computer."
$msg=6
if $allowExit<2 then
$msg=msgbox(36,"Exit SRP Enforcer?","Your system is currently " & $LockedModeOnOFF & @crlf & "This policy will remain in-force until changed." & @crlf & @crlf &"Exit now?",20)
endif
if $msg=6 then exit

Case $ComboMinutesRemain
$msg = GUIGetMsg()
Switch GUICtrlRead($ComboMinutesRemain)
Case "10"
IniWrite($inifile, "General", "UnlockTimeout", "10")
Case "20"
IniWrite($inifile, "General", "UnlockTimeout", "20")
EndSwitch
Case $ComboRememberPass
$msg = GUIGetMsg()
Switch GUICtrlRead($ComboRememberPass)
Case "5"
IniWrite($inifile, "General", "PasswordRetention", "5")
Case "10"
IniWrite($inifile, "General", "PasswordRetention", "10")
EndSwitch
Case $CheckboxDisableTaskMgr
If GUICtrlRead($CheckboxDisableTaskMgr)=$GUI_CHECKED Then
RegWrite("HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionPoliciessystem","DisableTaskMgr","REG_DWORD",1)
IniWrite($inifile, "General", "EnableTaskManager","0")
EndIf
If GUICtrlRead($CheckboxDisableTaskMgr)=$GUI_UNCHECKED Then
RegWrite("HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionPoliciessystem","DisableTaskMgr","REG_DWORD",0)
IniWrite($inifile, "General", "EnableTaskManager","1")
EndIf
Case $CheckboxPreventExit
If GUICtrlRead($CheckboxPreventExit)=$GUI_CHECKED And IniRead($inifile, "General", "AllowExit","")=1 Then IniWrite($inifile, "General", "AllowExit", "0")
If GUICtrlRead($CheckboxPreventExit)=$GUI_UNCHECKED And IniRead($inifile, "General", "AllowExit","")=0 Then IniWrite($inifile, "General", "AllowExit", "1")
Case $ButtonRemoveWhitelist
$ListContents = GUICtrlRead($ListWhitelist)
_GUICtrlListBox_DeleteString($ListWhitelist, _GUICtrlListBox_GetCaretIndex($ListWhitelist))
IniDelete($inifile, "CustomPolicies", $ListContents)
Case $ButtonAddWhitelist
$msg = GUIGetMsg()
Switch GUICtrlRead($ButtonAddWhitelist)
Case "Add File"
$varFile = FileOpenDialog("Select executable to add to the Whitelist.", @WindowsDir & "", "All Files(*.*) | Known Executables (*.A6P;*.AC;*.AS;*.ACR;*.ACTION)", 1)
GUICtrlSetData($ListWhitelist, $varFile)
IniWrite($inifile, "CustomPolicies", $varFile, "1")
Case Else
Local $varFolder = FileSelectFolder("Choose a folder.", "", 2+4)
GUICtrlSetData($ListWhitelist, $varFolder)
IniWrite($inifile, "CustomPolicies", $varFolder, "1")
EndSwitch
Case $IconHelp
EndSwitch
WEnd

Without freezing my GUI.

Edited by telmob

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

Hmm I don't have time to decypher this right now, but I'm guessing you are talking about nested While loops. If so the principle is quite simple. Just be careful you don't get stuck in an infinite loop.

Dim $bHeads = True

While $bHeads
    While $bHeads
        ; Toss a coin
        If Random(0, 1, 1) Then $bHeads = Not $bHeads ; Heads or Tails?
        ConsoleWrite($bHeads & @LF)
    WEnd

    ; Toss the coin again
    If Random(0, 1, 1) Then $bHeads = Not $bHeads ; Heads or Tails?
    ConsoleWrite($bHeads & @LF)
WEnd

You probably don't want this because inserting one of your loops in a function (which you can call from within your first loop) might be a better solution.

Edited by czardas

Share this post


Link to post
Share on other sites

Thank you for your reply.

I have tried to call a function from my main 'while' (the second one i posted) but i guess it goes into an infinite loop. My GUI gets stalled and there's nothing i can do in it, not even exit.

The problem is that i need the first 'while' to be permanentely active and not dependent on any trigger. Because it basically tells my script that is has reached the time limit being in unlocked mode and it will activate locked mode. But i can't find a way to do it myself, that's why i searched for this example here on the forum and this is perfect, except i can't also place it in my other 'while' :)

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

I guessed you might have done that which is why I mentioned the infinite loop scenario. There are several possibilities for keeping things alive, but once inside a nested loop, you must exit that loop in order to return to the first loop. Instead of trying to create two simultaneously running loop processes (which is impossible in AutoIt), you could use something like AdlibRegister to check the time out. Also you can interrupt loops in various ways. Above I use a boolean flag ($bHeads => True or False) to trigger when I exit each loop. There is a good article about this here: Interrupting a Running Function

Edited by czardas

Share this post


Link to post
Share on other sites

You need to explain where you want the second while loop included in your first one. Because looking at the top while loop example it looks like it should be in a function or called by a button, and in the bottom one, not sure where you'd try to call that loop from.


If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites

#6 ·  Posted (edited)

Sorry i took so long to reply, i was cooking :)

I guessed you might have done that which is why I mentioned the infinite loop scenario. There are several possibilities for keeping things alive, but once inside a nested loop, you must exit that loop in order to return to the first loop. Instead of trying to create two simultaneously running loop processes (which is impossible in AutoIt), you could use something like AdlibRegister to check the time out. Also you can interrupt loops in various ways. Above I use a boolean flag ($bHeads => True or False) to trigger when I exit each loop. There is a good article about this here: Interrupting a Running Function

I understood your $bHeads example. But if i use a simillar solution the 'timeout' i'm trying to implement will only be active when one loop (while) is active, right? And i need to keep them both active. I'm trying to learn how exactly AdlibRegister works. The problem is that i cannot interrupt a running function.

For example. What i'm trying to accomplish is to set a timeout when the program is unlocked. But this timeout has to be active whether the GUI (first loop) is active or not.

You need to explain where you want the second while loop included in your first one. Because looking at the top while loop example it looks like it should be in a function or called by a button, and in the bottom one, not sure where you'd try to call that loop from.

I want the first included in the second, it really doesn't matter where it is placed, just as long as its permanentely active if the $unlockTimeout is set (which is IniRead("SRPE.ini", "General", "UnlockTimeout"). And i've tried pointing a function to it when the ini reads UnlockTimeout>1, but it stalls my gui......

So, the GUI sets the option to write the inifile UnlockTimeout=10 (minutes) and from that moment on the loop will check continuously if UnlockTimeout>0, if it is, it will count the minutes, and when it reaches 0, it locks the program again, as such:

iniwrite("SRPE.ini", "General", "LockedMode", "1")
RegWrite($hklm & "SOFTWAREPoliciesMicrosoftWindowsSaferCodeIdentifiers","DefaultLevel","REG_DWORD",0)
Edited by telmob

Share this post


Link to post
Share on other sites

telmob,

The following demonstrates the use of an adlibregister to control a gui.

; *** Start added by AutoIt3Wrapper ***
#include <GUIConstantsEx.au3>
; *** End added by AutoIt3Wrapper ***
;
;

#AutoIt3Wrapper_Add_Constants=n

local $gui010 = guicreate('Demonstrate Adlibregister')
local $lbl010 = guictrlcreatelabel('App UnLocked',100,50,200,30)
                guictrlcreatebutton('My Button',100,100,200,30)
                guisetstate()

local $msg, $timeout_timer = 3000
local $timeout = false

adlibregister('switcher',$timeout_timer)

while guigetmsg() <>    $gui_event_close
    if $timeout then
        if guictrlread($lbl010) = 'App UnLocked' then
            guictrlsetdata($lbl010,'App Locked')
            guisetstate(@sw_disable,$gui010)
            adlibregister('switcher',$timeout_timer)
            $timeout = false
        Else
            guictrlsetdata($lbl010,'App UnLocked')
            guisetstate(@sw_enable,$gui010)
            adlibregister('switcher',$timeout_timer)
            $timeout = False
        EndIf
    EndIf
WEnd

func switcher()
    $timeout = True
endfunc

kylomas


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

That is a very cool example. The AdlibRedister in the help file really doesn't give a very complete example. I'll try to adjust my gui to use AdlibRegister and see how it goes from there.

Thank you kylomas ;)

Share this post


Link to post
Share on other sites

telmob,

Good Luck...keep in mind that the primary purpose of the help file is to define syntax and function. Some examples are usually given, but cannot possibly cover all applications of the subject.

kylomas


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

telmob,

Good Luck...keep in mind that the primary purpose of the help file is to define syntax and function. Some examples are usually given, but cannot possibly cover all applications of the subject.

kylomas

Yeah, i know, i just wanted a more 'palpable' example in the help file, but now that understand it, i can see its enough.

Your example doesn't do it for me... :(

The first loop i posted (first post) allows me to reboot the computer and continues counting. So in case i'm installing a new app that needs to reboot, it doesn't stop the app from doing any installation procedure @ boot.

These timers are a bit confusing to me. Any idea in how i can do this? I also don't understand how i can convert minutes in seconds. Will a divide do (/)?

Share this post


Link to post
Share on other sites

telmob,

My purpose was to demonstrate one possible use of an adlib. I do not see how you are accumulating time between instances of your script from the code that you've shown.

Time calc's (credit BrewmanNH)

local $st = timerinit()                     ; start first timed interval
sleep(6000)
local $intrvl1 = timerdiff($st)             ; # of milli secs for 1st interval
$st = timerinit()                           ; start second interval
sleep(3000)
local $intrvl2 = timerdiff($st)             ; # of milli secs for 2nd interval
local $duration = $intrvl1 + $intrvl2       ; accumulation of monitored time

consolewrite('! Duration = ' & stringformat( '%02i:%02i:%02i', _
                                                floor( ($duration/1000)/60^2), _
                                                mod(   ($duration/1000)/60,60 ), _
                                                mod(   ($duration/1000), 60 )) & @lf)

kylomas


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

Thank you for your terrific help and sorry for being asking for so much help.

I believe i have a solution that works nicely, i'll post tomorrow.

Again, thank you for your help.

Share this post


Link to post
Share on other sites

telmob,

No problem, you're obviously seeking knowledge, not someone to do it for you. I'll be interested in seeing your solution.

kylomas


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

#14 ·  Posted (edited)

I'm stuck again in my timer.... :D

Right about here:

If $_MinCalc <> $_Minutes Or $_SecCalc <> $_Seconds Then
$_Minutes = $_MinCalc
$_Seconds = $_SecCalc
GUICtrlSetData ( $Time2Lock, StringFormat ( "%02u" & ":" & "%02u", $_Minutes, $_Seconds ) )
EndIf

It continues to display the countdown time and doesn't stop ever.

How can i set it to stop if the following occurs? :

IniRead($inifile, "General", "Locked", "") = 1

Full timer example here:

#include <WindowsConstants.au3>

Global $initimeout=iniread("SRPE.ini", "General", "UnlockTimeout", "")*60*1000
Global $_CompteArebour = $initimeout, $_Minutes, $_Seconds

$_GuiCountDown = GUICreate ( "CountDown...", 500, 200, @DesktopWidth/2 -250, @DesktopHeight/2 -100, $WS_EX_TOPMOST )
$Time2Lock = GUICtrlCreateLabel("to auto-lock", 176, 16, 60, 17)
$Time2Lock = GUICtrlCreateLabel("00:00", 144, 16, 31, 17)
GUICtrlSetColor(-1, 0xFF0000)
GUISetState ( )
WinSetOnTop ( $_GuiCountDown, "", 1 )
$TimeTicks = TimerInit ( )

While 1
_Check ( )
Sleep ( 200 )
WEnd

Func _Check ( )
$_CompteArebour -= TimerDiff ( $TimeTicks )
$TimeTicks = TimerInit ( )
Local $_MinCalc = Int ( $_CompteArebour / ( 60 * 1000 ) ), $_SecCalc = $_CompteArebour - ( $_MinCalc * 60 * 1000 )
$_SecCalc = Int ( $_SecCalc / 1000 )
If $_MinCalc <= 0 And $_SecCalc <= 0 Then
GUICtrlSetData ( $Time2Lock, "Bye !" )
Sleep ( 1000 )
Exit
Else
If $_MinCalc <> $_Minutes Or $_SecCalc <> $_Seconds Then
$_Minutes = $_MinCalc
$_Seconds = $_SecCalc
GUICtrlSetData ( $Time2Lock, StringFormat ( "%02u" & ":" & "%02u", $_Minutes, $_Seconds ) )
EndIf
EndIf
EndFunc
Edited by telmob

Share this post


Link to post
Share on other sites

#15 ·  Posted (edited)

Sorry for being a pain, but this is killing me, i've tried everything.

Is there any way to interrupt the time countdown in background in my previous example?

Edited by telmob

Share this post


Link to post
Share on other sites

#16 ·  Posted (edited)

telmob,

In your main loop you need to decide whether or not to run _check logically. Something like

if $timeout <> 'Locked' then _check()
If I am understanding the issue, that is.

kylomas

edit: additional info

The example that I posted in #7 starts and stops a timer based on a button...you need to do the same based on whatever your criteria are.

Edited by kylomas

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

#17 ·  Posted (edited)

Thank you for your response Kylomas.

telmob,

In your main loop you need to decide whether or not to run _check logically. Something like

if $timeout <> 'Locked' then _check()
If I am understanding the issue, that is.
Its set to run if the ini file has unlocktimeout > 0, the problem is that i can't get it to stop.

The example that I posted in #7 starts and stops a timer based on a button...you need to do the same based on whatever your criteria are.

I know, and its really cool, but can i put the running timer that can be interrupted in the gui? Edited by telmob

Share this post


Link to post
Share on other sites

Looking again at your first post, there seems to be some quite complicated looking code in there (that you are trying to combine). We have tried to address general questions regarding your script, but I have to admit that I find it very hard to understand the purpose behind this code. Perhaps more details about the reason you need this, where it will be used, and under what circumstances would help us to help you.

Share this post


Link to post
Share on other sites

#19 ·  Posted (edited)

Hello Czardas. I have a script with a GUI and a tray icon with some items in it.

The script's main function is to activate the Software Restriction Policy and configure it, so the user has a little application that allows him to easily set allowed files and folders that can run in the computer. Ofcourse the main system folders are allowed by default for stability sake.

The tray icon has the following options:

Lock - Only allowed files/folders will be able to run

Unlock - All files/folders can run

Configure - Opens GUI with different settings

Exit

The main GUI has several options. (attached)

I just want the timer you see in the gui to stop the background countdown.

I have it set to stop (and hide the timer countdown), when the system is set to 'Lock' or i untick the 'Enable unlock timeout' option, and to start when i tick that option, but when i untick and tick again, the timer continues from where it stopped and not from the startup time set.

The 'Enable unlock timeout" option writes 'unlocktimeout = 30" in the ini file. And when i untick it, it writes '0'. The timer reads the 'unlocktimeout' value and starts to count from there. When the value is at '0' (or the system is 'Locked'), the timer should stop, but it doesn't.

post-65971-0-81243800-1353709453_thumb.p

Edited by telmob

Share this post


Link to post
Share on other sites

#20 ·  Posted (edited)

Okay thanks for the explanation. Restriction policies are something I haven't had much experience with, so that's why I was confused. I will have a look at it tomorrow because I'm too tired to look at it right now.

Edited by czardas

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  
Followers 0