Jump to content

Enable and Disable function with a GUI checkbox (CHECKED/UNCHECKED)


Recommended Posts

Hi all, I am trying to enable a function TestFunction1() when a GUI checkbox $AnalysisCheckbox is CHECKED, and disable when checkbox is UNCHECKED. Needs to occur once the 'Start' button is pressed. Any ideas? I can't find anything on this. Thanks in advance. 

 

Code below: 

#include <MsgBoxConstants.au3>
#include <GUIConstantsEx.au3>

#Region ### START Koda GUI section ### Form= V2.0
Global $WindowTitle = GUICreate("TEST", 300, 200, -1, -1)
Global $AnalysisCheckbox = GUICtrlCreateCheckbox("Enable/Disable Function X", 10, 10, 300, 50)
GUICtrlSetState(-1, $GUI_CHECKED)
GUICtrlSetFont(-1, 14, 400, 0, "Georgia")
Global $StartButton = GUICtrlCreateButton("Start", 10, 70, 100, 100)
GUICtrlSetFont(-1, 14, 800, 0, "Georgia")
GUICtrlSetBkColor(-1, 0x00FF00)

GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit
        Case $GUI_EVENT_CLOSE
            Exit
        Case $StartButton
            ExitLoop
        Case $AnalysisCheckbox
            If GUICtrlRead ($AnalysisCheckbox) = 1 Then
                MsgBox(0,"","Enable Function")
            ElseIf GUICtrlRead ($AnalysisCheckbox) =4 Then
                MsgBox(0,"","Disable Function")
            EndIf
    EndSwitch
WEnd

TestFunction1()
TestFunction2()

Func TestFunction1()
    MsgBox(0,"","TestFunction 1 TEXT")
EndFunc
Func TestFunction2()
    MsgBox(0,"","TestFunction 2 TEXT")
EndFunc

Link to comment
Share on other sites

  • Developers

Just look at the example in the HelpfIle for GUICtrlCreateCheckbox() and you have your answer how this needs to be solved. ;) 

Jos

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

The _IsChecked() function returns a numeric value. For binary (true/false) answers, for example "If _IsChecked($idCheckbox)", we want a return of 0 (false) or 1 (true). However, GUICtrlRead returns a 1 if the checkbox is checked, and 4 if the box is unchecked. Don't know how familiar you are with bitwise operations, but the BitAND compares the returned value (1 or 4) to $GUI_CHECKED (1) and if they are the same the function returns 1, if not returns 0.

A similar result is is obtained using the following modification to the example, without the BitAND (Uncomment line 24 to see the return value):

#include <GUIConstantsEx.au3>
#include <MsgBoxConstants.au3>

Example()

Func Example()
    ; Create a GUI with various controls.
    Local $hGUI = GUICreate("Example", 300, 200)

    ; Create a checkbox control.
    Local $idCheckbox = GUICtrlCreateCheckbox("Standard Checkbox", 10, 10, 185, 25)
    Local $idButton_Close = GUICtrlCreateButton("Close", 210, 170, 85, 25)

    ; Display the GUI.
    GUISetState(@SW_SHOW, $hGUI)

    ; Loop until the user exits.
    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE, $idButton_Close
                ExitLoop

            Case $idCheckbox
;~              MsgBox($MB_SYSTEMMODAL, "Test", GUICtrlRead($idCheckbox))
                If (_IsChecked($idCheckbox) = $GUI_CHECKED) Then             
                    MsgBox($MB_SYSTEMMODAL, "", "The checkbox is checked.", 0, $hGUI)
                ElseIf (_IsChecked($idCheckbox) = $GUI_UNCHECKED) Then
                    MsgBox($MB_SYSTEMMODAL, "", "The checkbox is not checked.", 0, $hGUI)
                EndIf

        EndSwitch
    WEnd

    ; Delete the previous GUI and all controls.
    GUIDelete($hGUI)
EndFunc   ;==>Example

Func _IsChecked($idControlID)
    Return GUICtrlRead($idControlID)
EndFunc   ;==>_IsChecked

 

Edited by Sidley
Changed to single '=' as per Melba23's suggestion
Link to comment
Share on other sites

  • Moderators

Sidley,

There is no need to use the "==" operator in your comparisons - a single "=" will suffice. The double version is for comparing strings with case sensitivity and here you are comparing integers. See here for more details: https://www.autoitscript.com/autoit3/docs/intro/lang_operators.htm

M23 

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see 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

 

Link to comment
Share on other sites

Why not check directly, without yet another function?

Case $idCheckbox
If GUICtrlRead($idCheckbox) = $GUI_CHECKED Then
MsgBox($MB_SYSTEMMODAL, "", "The checkbox is checked.", 0, $hGUI)
Else
MsgBox($MB_SYSTEMMODAL, "", "The checkbox is not checked.", 0, $hGUI)
EndIf

 

Edited by careca
Spoiler

Renamer - Rename files and folders, remove portions of text from the filename etc.

GPO Tool - Export/Import Group policy settings.

MirrorDir - Synchronize/Backup/Mirror Folders

BeatsPlayer - Music player.

Params Tool - Right click an exe to see it's parameters or execute them.

String Trigger - Triggers pasting text or applications or internet links on specific strings.

Inconspicuous - Hide files in plain sight, not fully encrypted.

Regedit Control - Registry browsing history, quickly jump into any saved key.

Time4Shutdown - Write the time for shutdown in minutes.

Power Profiles Tool - Set a profile as active, delete, duplicate, export and import.

Finished Task Shutdown - Shuts down pc when specified window/Wndl/process closes.

NetworkSpeedShutdown - Shuts down pc if download speed goes under "X" Kb/s.

IUIAutomation - Topic with framework and examples

Au3Record.exe

Link to comment
Share on other sites

Not sure if the following addresses what is really behind the OP's question, but here goes.

When I first started trying to interrupt functions, I learnt about and used the Adlib functions, but that was imperfect ... for instance, Adlib stops when a MsgBox is running or when doing some kind of query where you are waiting for a response. I then gravitated to a small secondary STOP button floating GUI and executable that wrote to an INI file, that the first program checked repeatedly in the function. That worked much better, but of course that means two EXE files.

What I discovered one day, quite by accident, was that you can use a Checkbox to achieve what you want. Not because you click the checkbox and you get an instant value returned which you can act on, you don't until the function has finished. But you can use GUICtrlRead in your function code at various intervals, to check the state of that Checkbox, regardless of any value change. So instead of doing INI write and read to determine whether to interrupt a function or not, I just check the state of a checkbox using GUICtrlRead.

Of course that won't help those who have the text on a START button changed to STOP when they start some function code, and want to have that button stop the function. But having a STOP checkbox alongside the START button, works really well ... so long as you regularly poll the state of that checkbox using GUICtrlRead.

Note, that the checkbox does not solve the MsgBox or the system waiting for a response issue, but you can set it (enable it) at almost any time, and you can avoid click timing issues due to delayed button response.

Edited by TheSaint

Make sure brain is in gear before opening mouth!
Remember, what is not said, can be just as important as what is said.

Spoiler

What is the Secret Key? Life is like a Donut

If I put effort into communication, I expect you to read properly & fully, or just not comment.
Ignoring those who try to divert conversation with irrelevancies.
If I'm intent on insulting you or being rude, I will be obvious, not ambiguous about it.
I'm only big and bad, to those who have an over-active imagination.

I may have the Artistic Liesense ;) to disagree with you. TheSaint's Toolbox (be advised many downloads are not working due to ISP screwup with my storage)

userbar.png

Link to comment
Share on other sites

5 hours ago, Sidley said:

The point of the post was to show what the BitAND was doing, which was what @Soil_Person was having trouble

I agree.

@Soil_Person A BitAND operation in this case just checks for the existence of a flag in a "magic" number, to understand how this works first you have to learn how binary works, then bit-operations are the next step. There are many tutorials and sources you can use to learn, however it is not necessary for you to understand how it works to use it :)

I happened to have made a very simple function, which allows you to check if a flag exists in a magic number, you can use this instead of the BitAND function:

; #FUNCTION# ====================================================================================================================
; Name ..........: IsMgcNumPresent
; Description ...: Checks if a number is a present in a number (Magic numbers aka Powers of 2)
; Syntax ........: IsMgcNumPresent($iNumber, $iMagicNumber)
; Parameters ....: $iNumber             - Number to check if it exists in $iMagicNumber.
;                  $iMagicNumber        - The number which might contain $iNumber.
; Return values .: Success: True
;                  Failure: False
; Author ........: Damon Harris (TheDcoder)
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........: https://git.io/vPFjk
; Example .......: Yes, see IsMgcNumPresent_Example.au3
; ===============================================================================================================================
Func IsMgcNumPresent($iNumber, $iMagicNumber)
    Return BitAND($iMagicNumber, $iNumber) = $iNumber
EndFunc

Example for reading checkbox state:

; This function will return True if the passed checkbox is checked
Func IsCheckedbox($idBox)
    Local $iState = GUICtrlRead($idBox)
    Return IsMgcNumPresent($GUI_CHECKED, $iState)
EndFuc

 

EasyCodeIt - A cross-platform AutoIt implementation - Fund the development! (GitHub will double your donations for a limited time)

DcodingTheWeb Forum - Follow for updates and Join for discussion

Link to comment
Share on other sites

4 hours ago, TheSaint said:

I just check the state of a checkbox using GUICtrlRead.

Personally as a CB acts like a button, I use WM_COMMAND  :)

#include <GUIConstantsEx.au3>
#include <WindowsConstants.au3>

Global $stop = 0, $exit = 0

GUICreate("My GUI", 200, 100) 
$label = GUICtrlCreateLabel("", 30, 20, 20, 20)
$label2 = GUICtrlCreateLabel("I'm gone", 60, 20, 80, 20)
$btn = GUICtrlCreateCheckbox("stop", 10, 50, 50, 20)
$btn2 = GUICtrlCreateButton("exit", 120, 50, 50, 20)
GUISetState()  

GUIRegisterMsg($WM_COMMAND, "_WM_COMMAND")

For $i = 1 to 1000
  While $stop and not $exit
       Sleep(10)
  Wend
  If $exit Then Exitloop
  GuiCtrlSetData($label, $i)
  Sleep(300)
Next
Msgbox(0,"", "Exit !")

Func _WM_COMMAND($hWnd, $Msg, $wParam, $lParam)
 #forceref $hWnd, $Msg, $lParam
 Switch BitAND($wParam, 0x0000FFFF)
    Case $btn
        $stop =  not $stop
        GuiCtrlSetData($label2, $stop ? "Hey, I'm here !" : "I'm gone")  
        GuiCtrlSetData($btn, $stop ? "start" : "stop")  
     Case $btn2
        $exit = 1
EndSwitch
  Return 'GUI_RUNDEFMSG'
EndFunc

 

Link to comment
Share on other sites

https://www.autoitscript.com/wiki/FAQ#How_can_I_test_if_checkbox_.2F_radiobutton_is_checked.3F

EDIT:

#include <MsgBoxConstants.au3>
#include <GUIConstantsEx.au3>

Global $enabled_func1 = True

#Region ### START Koda GUI section ### Form= V2.0
Global $WindowTitle = GUICreate("TEST", 300, 200, -1, -1)
Global $AnalysisCheckbox = GUICtrlCreateCheckbox("Enable/Disable Function X", 10, 10, 300, 50)
GUICtrlSetState(-1, $GUI_CHECKED)
GUICtrlSetFont(-1, 14, 400, 0, "Georgia")
Global $StartButton = GUICtrlCreateButton("Start", 10, 70, 100, 100)
GUICtrlSetFont(-1, 14, 800, 0, "Georgia")
GUICtrlSetBkColor(-1, 0x00FF00)

GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###

While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit
        Case $GUI_EVENT_CLOSE
            Exit
        Case $StartButton
            ExitLoop
        Case $AnalysisCheckbox
            $enabled_func1 = IsChecked($AnalysisCheckbox)
            If $enabled_func1 Then
                MsgBox(0,"","Enable Function")
            Else
                MsgBox(0,"","Disable Function")
            EndIf
    EndSwitch
WEnd

TestFunction1()
TestFunction2()

Func TestFunction1()
    If Not $enabled_func1 Then Return
    MsgBox(0,"","TestFunction 1 TEXT")
EndFunc
Func TestFunction2()
    MsgBox(0,"","TestFunction 2 TEXT")
EndFunc

Func IsChecked($control)
    Return BitAND(GUICtrlRead($control), $GUI_CHECKED) = $GUI_CHECKED
EndFunc   ;==>IsChecked

 

Edited by Zedna
Link to comment
Share on other sites

On 6/5/2020 at 1:56 AM, mikell said:

Personally as a CB acts like a button, I use WM_COMMAND  :)

Goodo, but I'm not using it as a button really ... because it is not about a click response, but rather a state check.

I don't know enough to know the full difference between OnEvent like you are using and Adlib, which I have used often in the past.

The issue I mostly get around with using the GUICtrlRead function, is that of accidental or double clicking, which can require some elaborate code to work-around ... usually occurs due to system delays, and what I call Button Memory, which I am sure we have all experienced. Using GUICtrlRead means that you aren't relying on a button push being recognized by the system.

By Button Memory, I mean you got no visible clue that the button got clicked, because the system is too busy doing something else, but when some seconds later it responds, it recalls you clicked the button and acts accordingly. However, a user or even yourself, might meanwhile think you did not click properly, so click again, and so the system sees two clicks when it returns, so you get a STOP swiftly followed by an unwanted START again.

Edited by TheSaint

Make sure brain is in gear before opening mouth!
Remember, what is not said, can be just as important as what is said.

Spoiler

What is the Secret Key? Life is like a Donut

If I put effort into communication, I expect you to read properly & fully, or just not comment.
Ignoring those who try to divert conversation with irrelevancies.
If I'm intent on insulting you or being rude, I will be obvious, not ambiguous about it.
I'm only big and bad, to those who have an over-active imagination.

I may have the Artistic Liesense ;) to disagree with you. TheSaint's Toolbox (be advised many downloads are not working due to ISP screwup with my storage)

userbar.png

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...