Jump to content

Recommended Posts

Posted

image.png.5e8073b470330f4b14c1daa782e8cfbb.png

#include <GuiConstants.au3>
#include <GuiIPAddress.au3>
#include <WindowsConstants.au3>
Opt("MustDeclareVars", 1)
test()
Func test()
    Local $hgui, $nMsg, $iBtn_Get, $hIPAddress
    $hgui = GUICreate("IP Address Control Example", 500, 150)
    Local $hIPAddress = _GUICtrlIpAddress_Create($hgui, 10, 10, 200, 20)
    _GUICtrlIpAddress_Set($hIPAddress, @IPAddress1)
    $iBtn_Get = GUICtrlCreateButton("Get IP", 220, 10, 75, 20)

    GUICtrlCreateInput("1234 1234 1234 1234 1234", 10, 40, 200)
    GUICtrlCreateButton("Get USPS", 220, 40, 75, 20)
    GUICtrlCreateInput("1234 1234 1234 1234 1234 12", 10, 70, 200)
    GUICtrlCreateButton("Get USPS", 220, 70, 75, 20)

    GUISetState(@SW_SHOW)

    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                GUIDelete($hgui)
                ExitLoop
            Case $iBtn_Get
                Local $sIP = _GUICtrlIpAddress_Get($hIPAddress)
                MsgBox(4160, "Information", "IP Address entered: " & $sIP)
        EndSwitch
    WEnd
EndFunc   ;==>test

 

I'd like to have an input control that behaves like the one for IPv4 ( grouping the octets ) grouping  the 4 symbols of the number and the optional 2 at the end. Because the number can be 20 or 22 char long.

Help :baby:

Follow the link to my code contribution ( and other things too ).
FAQ - Please Read Before Posting.
autoit_scripter_blue_userbar.png

Posted (edited)

This behaves nicely 

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

Global $idInput = -1

Exit Test2()
Func Test2()
    Local $hgui = GUICreate("USPS thing", 340, 100)
    $idInput = GUICtrlCreateInput("1234 1234 1234 1234 1234 17", 10, 35, 200, 20)
    GUICtrlSetLimit(-1, 27) ; 22 digits + 5 spaces
;~  GUICtrlSetBkColor(-1, 0x667788)
    Local $idBttn = GUICtrlCreateButton("Validate USPS number", 210, 35, 120, 20)
    GUISetState()
    GUIRegisterMsg($WM_COMMAND, "_WM_COMMAND")
    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                GUIDelete($hgui)
                ExitLoop
            Case $idBttn
                If _USPS_Mod10_Check(GUICtrlRead($idInput)) Then
                    MsgBox(64, "Valid", "Checksum Passed! This is a validly formatted USPS number.", 60, $hgui)
                Else
                    ConsoleWrite('- the last digit should have been ' & @extended & @CRLF)
                    MsgBox(16, "Error", "Checksum Failed! Please check for typos.", 60, $hgui)
                EndIf
        EndSwitch
    WEnd
EndFunc   ;==>Test2

Func _WM_COMMAND($hWnd, $iMsg, $wParam, $lParam)
    Local $iIDFrom = BitAND($wParam, 0xFFFF)
    Local $iCode = BitShift($wParam, 16)

    If $iIDFrom = $idInput And $iCode = $EN_CHANGE Then
        Local $aSel = _GUICtrlEdit_GetSel($idInput)
        Local $iPos = $aSel[0]

        Local $sCurrent = GUICtrlRead($idInput)

        ; 1. REGEX: Remove everything that is NOT a digit [^0-9]
        Local $sClean = StringRegExpReplace($sCurrent, "[^0-9]", "")

        ; 2. REGEX: Insert space every 4 digits
;~      Local $sFormatted = StringRegExpReplace($sClean, "(.{4})", "$1 ")
        Local $sFormatted = StringRegExpReplace($sClean, ".{4}", "$0 ") ; pixelsearch
        $sFormatted = StringStripWS($sFormatted, 2) ; Remove trailing space

        If $sCurrent <> $sFormatted Then
            GUICtrlSetData($idInput, $sFormatted)

            ; 3. Adjust cursor position if text length changed
            If StringLen($sFormatted) > StringLen($sCurrent) Then $iPos += 1
            If StringLen($sFormatted) < StringLen($sCurrent) Then $iPos -= 1

            _GUICtrlEdit_SetSel($idInput, $iPos, $iPos)
        EndIf
    EndIf
    Return $GUI_RUNDEFMSG
EndFunc   ;==>_WM_COMMAND

Func _USPS_Mod10_Check($sNum) ; The official USPS MOD10 Algorithm
    ; https://www.autoitscript.com/forum/topic/213428-_guictrlusps_create/#findComment-1549245
    $sNum = StringStripWS($sNum, 8) ; remove the spaces if any, and count 20 or 22
    If StringLen($sNum) <> 22 And StringLen($sNum) <> 20 Then Return SetError(1, -1, False)
    Local $aDigits = StringSplit($sNum, "")
    Local $iSum = 0, $iWeight = 3 ; The digit just before the check digit always gets a weight of 3

    ; Start from the one before the check digit and move LEFT
    For $i = $aDigits[0] - 1 To 1 Step -1
        $iSum += Int($aDigits[$i]) * $iWeight
        $iWeight = ($iWeight = 3 ? 1 : 3) ; Alternate weight between 3 and 1
    Next

    ; The check digit is the number needed to reach the next multiple of 10
    Local $iRemainder = Mod($iSum, 10)
    Local $iCalculatedCheck = ($iRemainder = 0) ? 0 : (10 - $iRemainder)

    ; Return True if the last digit matches the calculation
    Return SetError(0, $iCalculatedCheck, $iCalculatedCheck = Int($aDigits[$aDigits[0]]))
EndFunc   ;==>_USPS_Mod10_Check

...if you come up with something better, do post :)

Edit: added a validation function.

Edited by argumentum
better

Follow the link to my code contribution ( and other things too ).
FAQ - Please Read Before Posting.
autoit_scripter_blue_userbar.png

Posted

I suspect you might also want to fix the code to process the backspace when it's after a space to delete the last digit of the previous group.

Posted

Interesting
Here is my variation.

#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <GuiEdit.au3>
#include <WindowsConstants.au3>
#include <String.au3>

Global $idInput = -1

Test2()
Exit

Func Test2()
    Local $hgui = GUICreate("USPS thing", 300, 100)
    #forceref $hgui

    $idInput = GUICtrlCreateInput("", 20, 35, 260, 20)
    GUICtrlSetLimit(-1, 27) ; 22 digits + 5 spaces
    GUISetState()
    GUIRegisterMsg($WM_COMMAND, "_WM_COMMAND")

    While 1
        If GUIGetMsg() = $GUI_EVENT_CLOSE Then Exit
    WEnd
EndFunc   ;==>Test2

Func _WM_COMMAND($hWnd, $iMsg, $wParam, $lParam)
    #forceref $hWnd, $iMsg, $lParam

    Local $iIDFrom = BitAND($wParam, 0xFFFF)
    Local $iCode = BitShift($wParam, 16)

    If $iIDFrom = $idInput And $iCode = $EN_CHANGE Then
        Local $aSel = _GUICtrlEdit_GetSel($idInput)
        Local $iPos = $aSel[0]

        Local $sCurrent = GUICtrlRead($idInput)

        ; 1. REGEX: Remove everything that is NOT a digit [^0-9]
        Local $sClean = StringRegExpReplace($sCurrent, "[^0-9]", "")
        Local Static $sEmptyMask = '*********************'
        $sClean = $sClean & StringLeft($sEmptyMask, 21 - StringLen($sClean))

        ; 2. REGEX: Insert space every 4 digits
        ; Local $sFormatted = StringRegExpReplace($sClean, "(.{4})", "$1 ")
        Local $sFormatted = StringRegExpReplace($sClean, ".{4}", "$0.")
        $sFormatted = StringStripWS($sFormatted, 2) ; Remove trailing space

        If $sCurrent <> $sFormatted Then
            GUICtrlSetData($idInput, $sFormatted)

            ; 3. Adjust cursor position if text length changed
            If StringLen($sFormatted) > StringLen($sCurrent) Then $iPos += 1
            If StringLen($sFormatted) < StringLen($sCurrent) Then $iPos -= 1

            _GUICtrlEdit_SetSel($idInput, $iPos, $iPos)
        EndIf
    EndIf
    Return $GUI_RUNDEFMSG
EndFunc   ;==>_WM_COMMAND


ISSUES / TODO :

  1. to use 22 * not 21
  2. to see all * at start
  3. to works well when you type numbers
  4. to works well when you use delete/backspace key

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

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

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Posted
3 hours ago, pixelsearch said:

For the record, does this pattern works for you, without any group ?

Yes, worked well. Replaced the original with yours ( yes, I am the king of copy and paste :lol: ). Thanks.
Still don't know what's the difference, functionally. Unless I didn't test enough 🤔

44 minutes ago, mLipok said:

Here is my variation.

Didn't behave well and the one I put together ( yes, I edited the 2nd post ) works good enough.

But always welcome new ideas :) 

Follow the link to my code contribution ( and other things too ).
FAQ - Please Read Before Posting.
autoit_scripter_blue_userbar.png

Posted
43 minutes ago, argumentum said:

Didn't behave well and the one I put together ( yes, I edited the 2nd post ) works good enough.

But always welcome new ideas :) 

Thank you.
My version was a case study of sorts, a proof of concept that it could be achieved this way.
I'm curious if anyone can solve my list:

1 hour ago, mLipok said:

ISSUES / TODO :

  1. to use 22 * not 21
  2. to see all * at start
  3. to works well when you type numbers
  4. to works well when you use delete/backspace key

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

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

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

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
×
×
  • Create New...