Jump to content

SendEx - yet another alternative to the built-in Send function

Recommended Posts

As many are aware, the standard AutoIt Send() function can leave modifier keys (usually Shift, Alt, Ctrl) in a pressed-like state. While there are at least a few alternatives that can be found on this forum, as well as one in the Wiki (which i can't find at the moment), they have all failed me at some point, leaving a modifier key "stuck". So far i have had no issues with this function however.

; #FUNCTION# ====================================================================================================================
; Name ..........: _SendEx
; Description ...: alternative to built-in Send() function which prevents modifier keys from being left in a pressed state
; Syntax ........: _SendEx($sSendKeys[, $iTimeout[, $sReleaseKeys[, $hUser32Dll]]])
; Parameters ....: $sSendKeys           - string of keys to send in Send() format
;                  $hUser32Dll          - [optional] handle to user32.dll
;                  $iTimeout            - [optional] maximum time in ms to attempt to release pressed keys (minimum = 250)
;                  $sReleaseKeys        - [optional] comma seperated string of keys to release before issuing Send() (no spaces).
;                      defaults to: Shift, Ctrl, Alt, L Win, R Win
; Return values .: Success returns 1, else sets @error to 1 and returns an error message string
; Release date ..: 25-May-2014
; Modify date ...: 21-Sep-2014
; Author ........: iCode
; Modified by ...:
; Remarks .......:
; Related .......: Send()
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _SendEx($sSendKeys, $hUser32Dll = "", $iTimeout = 2000, $sReleaseKeys = "0x10,0x11,0x12,0x5B,0x5C")
    Local $bCloseDll, $sRet
    Local $iDelay = Opt("SendKeyDelay") + Opt("SendKeyDownDelay")
    If $iDelay < 50 Then $iDelay = 50
    Local $aReleaseKeys = StringSplit($sReleaseKeys, ",")
    If @error Then Return SetError(1, 0, "Failed to create release key array")
    If $hUser32Dll <> "user32.dll" Then
        $hUser32Dll = DllOpen("user32.dll")
        If @error Then Return SetError(1, 0, "Failed to open handle to user32.dll")
        $bCloseDll = True
    $sRet = __ReleaseKeys($aReleaseKeys, $iTimeout, $hUser32Dll)
    If Not @error Then
        $sRet = __ReleaseKeys($aReleaseKeys, $iTimeout, $hUser32Dll)
    If $bCloseDll Then DllClose("user32.dll")
    If $sRet Then Return SetError(1, 0, $sRet)
    Return 1

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name ..........: __ReleaseKeys
; Description ...: release pressed keys
; Syntax ........: __ReleaseKeys(Byref $aReleaseKeys, $iTimeout, $hUser32Dll)
; Parameters ....: $aReleaseKeys        - [in/out] An array of unknowns.
;                  $iTimeout            - An integer value.
;                  $hUser32Dll          - A handle value.
; Return values .: None
; Author ........: iCode
; Modified ......: 25-May-2014
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func __ReleaseKeys(ByRef $aReleaseKeys, $iTimeout, $hUser32Dll)
    If $iTimeout < 50 Then $iTimeout = 250
    Local $aRet, $hTimer = TimerInit()
    For $i = 0 To UBound($aReleaseKeys) - 1
        $aRet = DllCall($hUser32Dll, "short", "GetAsyncKeyState", "int", $aReleaseKeys[$i])
        If @error Then Return SetError(1, 0, "Dll call GetAsyncKeyState failed with key: " & $aReleaseKeys[$i])
        If BitAND($aRet[0], 0x8000) <> 0 Then
                DllCall($hUser32Dll, "int", "keybd_event", "int", $aReleaseKeys[$i], "int", 0, "long", 2, "long", 0)
                If @error Then Return SetError(1, 0, "Dll call keybd_event failed with key: " & $aReleaseKeys[$i])
                $aRet = DllCall($hUser32Dll, "short", "GetAsyncKeyState", "int", $aReleaseKeys[$i])
                If TimerDiff($hTimer) >= $iTimeout Then Return SetError(1, 0, "Time out limit reached")
            Until BitAND($aRet[0], 0x8000) = 0

Change log...

29-JUN-2014 - changed the order of the parameters for _SendEx, moving $sReleaseKeys to the last position

21-SEP-2014 - in the interest of efficiency, i removed the StringStripWS() function - $sReleaseKeys can no longer have spaces in the string

Edited by iCode

FUNCTIONS: WinDock (dock window to screen edge) | EditCtrl_ToggleLineWrap (line/word wrap for AU3 edit control) | SendEX (yet another alternative to Send( ) ) | Spell Checker (Hunspell wrapper) | SentenceCase (capitalize first letter of sentences)

CODE SNIPPITS: Dynamic tab width (set tab control width according to window width)

Link to post
Share on other sites
  • 1 month later...

the format is the same as Send()

FUNCTIONS: WinDock (dock window to screen edge) | EditCtrl_ToggleLineWrap (line/word wrap for AU3 edit control) | SendEX (yet another alternative to Send( ) ) | Spell Checker (Hunspell wrapper) | SentenceCase (capitalize first letter of sentences)

CODE SNIPPITS: Dynamic tab width (set tab control width according to window width)

Link to post
Share on other sites

It's quite clear it's an extension of Send(). I therefore see no reason to have an example if people are familiar with Send(). If not then they can look in the help file.

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

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
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By AthanBit
      I am Using Windows 10 on 32 Operating System
      On typing I use Alt + Shift so  to enable toggle typing in English and Greek
      i find it impossible to achieve the same function using autoit3 using Send ("!+")
      I would appreciate any help in solving this problem
      Also I would appreciate any help in switching to Greek language using the CAPS Key
      Thank you
    • By dejhost
      I am trying to automate a software called "LabelImg" (https://pypi.org/project/labelImg/).
      My autoit-script is started once I selected a folder with images within LabelImg. Pressing the button "Next Image" or pressing the shortcut "d" (https://github.com/tzutalin/labelImg#Hotkeys) jumps to the next image in the selected folder. This shall happen once per second.
      #include <Misc.au3> #include <MsgBoxConstants.au3> #include <AutoItConstants.au3> Opt("WinTitleMatchMode", 1) Local $hDLL = DllOpen("user32.dll") While 1 If _IsPressed("1B", $hDLL) Then ExitLoop Else Local $temp = WinActivate("labelImg") ConsoleWrite($temp & @CRLF) If WinActivate("labelImg") Then ConsoleWrite("All Set!" & @CRLF) EndIf ;Send("d") Local $temp = MouseClick($MOUSE_CLICK_RIGHT, 50, 200) If $temp <> 1 Then MsgBox(1, "$temp", $temp) ExitLoop EndIf Sleep(1000) EndIf WEnd DllClose($hDLL) So the Send ("d")-command and the MouseClick are alternative methods to jump to the next image. Both fail.
      Both ConsoleWrite's deliver proper feedback (I continiously get the handle and "All set" ).

      Could you tell me what I'm doing wrong? 
      Thank you.
    • By Danyfirex
      AT Command UDF - for control AT Modems, send SMS, get SMS
      #cs 1.0.0 2020/10/03 . First version - Danyfirex + mLipok 1.0.1 2020/10/04 . Added - Function - _ATCmd_IsPINReady - Danyfirex . Added - Function - _ATCmd_IsPINRequired - Danyfirex . Added - Function - _ATCmd_IsSIMInserted - Danyfirex . Added - Function - _ATCmd_IsSenderSupported - Danyfirex . Added - Function - _ATCmd_OnPINReques - Danyfirex . Added - Function - _ATCmd_SMS_ListTextMessages - Danyfirex . Added - Function - _ATCmd_SetPIN - Danyfirex . Added - Function - __ATCmd_GetPINCounter - Danyfirex - Added - ENUM - $ATCmd_ERR_PIN - Danyfirex - Added - ENUM - $ATCmd_ERR_SIM - Danyfirex . Changed - __ATCmd_ComposePDU() - using _ATCmd_UseUCS2() internally instead parameter - Danyfirex . Suplemented - #CURRENT# - Danyfirex . . 1.0.2 2020/10/05 . Added - ENUM - $ATCmd_MSGLIST_* - mLipok . Added - ENUM - $ATCmd_STATUS__* - mLipok - Added - ENUM - $ATCmd_ERR_PARAMETER - mLipok . Added - _ATCmd_UsePDU() - parameter validation - mLipok . Added - _ATCmd_UseUCS2() - parameter validation - mLipok . Added - more error logs . Changed - MagicNumber replaced with Standard UDF constants - mLipok . Small refactoring - mLipok . . 1.0.3 2020/10/05 . CleanUp - Danyfirex . . 1.0.4 2020/10/05 . Small refactoring - Danyfirex . CleanUp - Danyfirex . . 1.0.5 2020/10/23 . _ATCmd_FullLoging - mLipok . _ATCmd_CMEESetup() ... @WIP - mLipok . $ATCMD_STATUS_11_SUBSCRIBERNUMBER - mLipok . . 1.0.6 2020/10/25 . __ATCmd_CMSErrorParser() - mLipok . . @LAST https://www.nowsms.com/gsm-modem-cms-error-code-list https://m2msupport.net/m2msupport/at-command-to-enable-error-codes/ https://www.micromedia-int.com/en/gsm-2/73-gsm/669-cme-error-gsm-equipment-related-errors https://assets.nagios.com/downloads/nagiosxi/docs/ATCommandReference.pdf https://www.maritex.com.pl/product/attachment/40451/15b4db6d1a10eada42700f7293353776 https://www.multitech.net/developer/wp-content/uploads/2010/10/S000463C.pdf https://www.telit.com/wp-content/uploads/2017/09/Telit_AT_Commands_Reference_Guide_r24_B.pdf https://docs.rs-online.com/5931/0900766b80bec52c.pdf PDU Format / Testers / Encoders / decoders https://m2msupport.net/m2msupport/sms-at-commands/#pduformat http://smstools3.kekekasvi.com/topic.php?id=288 #ce  
    • By Drac89
      Hi Team, 
      I am trying to send credentials via autoit on a web app launched via IE. I am passing the credentials into variables and trying to send them send("$username") but username field isn't getting populated. But the password field, I can send the credential, also when I try ieformsetvalue and set the username wrt username field fetched, it's getting send but my login button remains greyed out. 
      Can angularjs keydown function interfere in the autoit send process and not allow the credentials passed if it's not typed out? This is a general question to understand if javascript or angular js etc could detect if the credentials are automated, then it might not detect it as a keydown? 
    • By diff
      still learning and trying to understand AutoIT but having problem in filling my PDF file.
      So my code looks like similar to this:
      Global $1 = "text text 44444444" Global $2 = "texting2 texting2" Global $3 = "newtext3 next3" ShellExecute ("C:\Users\XXX\Desktop\myPDF.pdf") WinWaitActive("MyPDF.pdf - Adobe Acrobat Reader DC") Send ("{TAB}") ClipPut($1) Send ("^v") Send ("{TAB 3}") ClipPut($2) Send("^v") Send ("{TAB}") ClipPut($3) Send("^v") So its fill my PDF form, the first field looks good, the code add the text text 4444, then second should be $2 with texting2 texting2 but for some reason the code uses for second and third field after TAB only variable $3.
      So, I receive in $2 and $3 for some reason same newtext3 next3 in both, why its skipping the variable $2? Maybe there also much better solution for instant text? Because Send writes with delay by letters which I don't like.
  • Create New...