why does not ControlSend () work, but it works great on educational tasks - autoit

I can’t understand why ControlSend () does not process in my example (Notepad ++), when it stopped showing itself in the tutorial examples (Notepad).
I cannot understand what is the error and the combat error, and it does not work out ControlSend ().
I work in windows 10
...
; увы эту строку не отрабатывает , но при это ошибку не выводит (not wotk :( )
;$hWnd5 =ControlSend($hWnd, "Tab", "[CLASS:SysTabControl32]", " new 1 ")
If Not $hWnd5 Then
MsgBox(4096, 'Сообщение', 'Строчка не отработала, ControlSend, завершаем работу скрипта')
Exit
EndIf
...
why this not work ???
all cod
; Запуск блокнота только так вызывается
Run('C:\kononov\Notepad++\notepad++.exe')
; Ожидание 5 секунд до появление окна блокнота и проверка
$hWnd = WinWait("[CLASS:Notepad++]", "", 5)
If Not $hWnd Then
MsgBox(4096, 'Сообщение', 'Окно не найдено, завершаем работу скрипта')
Exit
EndIf
;ControlClick(handle, button1);
; проверка открития
$hWnd1 = WinGetHandle($hWnd, "[CLASS:ToolbarWindow32; INSTANCE:1]")
If Not $hWnd1 Then
MsgBox(4096, 'Сообщение', 'Строчка окна не найдена,WinGetHandle, завершаем работу скрипта')
Exit
EndIf
; нажатие клавиши и проверка , нажатие клавиши "новый "
$hWnd3 =ControlClick($hWnd, "", "[CLASS:ToolbarWindow32]", "Left", 1,11, 12)
If Not $hWnd3 Then
MsgBox(4096, 'Сообщение', 'Строчка не отработала, ControlClick, завершаем работу скрипта')
Exit
EndIf
; нажатие клавиши и проверка , нажатие на рабочей поверхности
$hWnd4 =ControlClick($hWnd, "", "[CLASS:SysTabControl32]", "Left", 1,550, 50)
If Not $hWnd4 Then
MsgBox(4096, 'Сообщение', 'Строчка не отработала, ControlClick, завершаем работу скрипта')
Exit
EndIf
; Высылает строку символов в элемент увы строуон не реализует
$hWnd5 = ControlSend("[CLASS:Notepad++]", "Tab", "[CLASS:SysTabControl32]", "This is some text")
Send("asddas") ; вот эту срочку прекрастно отрабатывает
; увы эту строку не отрабатывает , но при это ошибку не выводит
;$hWnd5 =ControlSend($hWnd, "Tab", "[CLASS:SysTabControl32]", " new 1 ")
If Not $hWnd5 Then
MsgBox(4096, 'Сообщение', 'Строчка не отработала, ControlSend, завершаем работу скрипта')
Exit
EndIf
; Закрывает блокнот. ( пока открытым держим )
; WinClose($hWnd)
result

Try something like this:
You can skip parameters in ControlSend like the ControlID.
Opt('WinTitleMatchMode', 4)
ShellExecute('notepad++.exe', '', '', '', #SW_SHOW)
Sleep(100)
$h = WinGetHandle("[CLASS:Notepad++]", "")
ConsoleWrite($h & #CRLF)
ConsoleWrite("WA " & WinActivate($h) & #crlf)
ControlSend("[CLASS:Notepad++]", "", '', '^n')
Sleep(200)
ControlSend("[CLASS:Notepad++]", "", '', 'It works :-) yes')
;~ WinSetTitle($h, '', #UserName)

Related

I Need Help To Check A Script In

I Got A Problem With A Simple Login Gui In Autoit And I Really Cant Find Out Why It Wont Print The Username And Pass To A Text File
Here's The Code:
$gui = GuiCreate("Authenticate",120,170)
GUICtrlCreateLabel("Username:",10,10,50,20)
$username = GUICtrlCreateInput("",10,35,100,20)
GUICtrlCreateLabel("Password:",10,70,50,20)
$password = GUICtrlCreateInput("",10,95,100,20,0x0020)
$go = GuiCtrlCreateButton("OK",10,130,50,25)
$cancel = GuiCtrlCreateButton("Cancel",60,130,50,25)
GUISetState()
Do
$msg = GUIGetMsg()
If $msg = $go Then
FileWrite(#ScriptDir & '\userout.txt', $username)
FileWrite(#ScriptDir & '\passout.txt', $password)
Run("confirm.bat", "", #SW_HIDE)
EndIf
If $msg = $cancel Then
Exit
EndIf
Until GUIGetMsg() = $cancel
GuiDelete($gui)
I Tried To Use Different Lines Of Code But I Cant Find The Problem.
Thanks Beforehand
You have forgotten to read out the controls. In your script, you get the value of the control-id only.
$gui = GuiCreate("Authenticate",120,170)
GUICtrlCreateLabel("Username:",10,10,50,20)
$username = GUICtrlCreateInput("",10,35,100,20)
GUICtrlCreateLabel("Password:",10,70,50,20)
$password = GUICtrlCreateInput("",10,95,100,20,0x0020)
$go = GuiCtrlCreateButton("OK",10,130,50,25)
$cancel = GuiCtrlCreateButton("Cancel",60,130,50,25)
GUISetState()
Do
$msg = GUIGetMsg()
If $msg = $go Then
; FileWrite(#ScriptDir & '\userout.txt', $username) ; wrong
FileWrite(#ScriptDir & '\userout.txt', GUICtrlRead($username)) ; correct
; FileWrite(#ScriptDir & '\passout.txt', $password) ; wrong
FileWrite(#ScriptDir & '\passout.txt', GUICtrlRead($password)) ; correct
Run("confirm.bat", "", #SW_HIDE)
EndIf
If $msg = $cancel Then
Exit
EndIf
Until GUIGetMsg() = $cancel
GuiDelete($gui)

How to determine newline while reading a file

I have an AutoIt script that works, mostly. Reads a file, writes out what I want, but it does not preserve the original newline character. If I read a UNIX format file (LF only), it will write out a Windows format file (CR and LF).
Short of switching to something more robust, like Python, how do I solve this in AutoIt?
Opt("MustDeclareVars", 1) ;0 = no, 1 = require pre-declare
#include <File.au3>
#include <Array.au3>
Local $gInPath = $CmdLine[1]
Local $NumberOfLines = $CmdLine[2]
Local $gInDrive, $gInDir, $gInFName, $gInExt, $gOutPath
Local $gMsgBoxTitle = "Error in " & #ScriptName
Local $InLine
Local $LineCount
Local $oFileIn
Local $oFileOut
Local $FileStringAppend
If FileExists($gInPath) Then
Else
MsgBox(4096, $gMsgBoxTitle, "This file does not exist" & #CRLF & $gInPath)
Exit
EndIf
_PathSplit($gInPath, $gInDrive, $gInDir, $gInFName, $gInExt)
If $NumberOfLines >= 1000000 Then
$FileStringAppend = $NumberOfLines / 1000000 & "M"
ElseIf $NumberOfLines >= 1000 Then
$FileStringAppend = $NumberOfLines / 1000 & "K"
Else
$FileStringAppend = $NumberOfLines
EndIf
$gOutPath = _PathMake($gInDrive, $gInDir, $gInFName & "_" & $FileStringAppend, $gInExt)
If FileExists($gOutPath) Then
MsgBox(4096, $gMsgBoxTitle, "File already exists" & #CRLF & $gOutPath)
Exit
EndIf
$oFileIn = FileOpen($gInPath, 0)
$oFileOut = FileOpen($gOutPath, 1)
; Check if file opened for reading OK
If $oFileIn = -1 Then
MsgBox(4096, $gMsgBoxTitle, "Unable to open file for read" & #CRLF & $gInPath)
Exit
EndIf
; Check if file opened for writing OK
If $oFileOut = -1 Then
MsgBox(4096, $gMsgBoxTitle, "Unable to open file for write." & #CRLF & $gOutPath)
Exit
EndIf
; Read in lines of text until the EOF is reached
$LineCount = 0
While 1
$InLine = FileReadLine($oFileIn)
$LineCount += 1
If #error = -1 Then ExitLoop
If $LineCount > $NumberOfLines Then ExitLoop
FileWriteLine($oFileOut, $InLine & #CRLF)
WEnd
FileClose($oFileIn)
FileClose($oFileOut)
Looking at the function documentation at this link - https://www.autoitscript.com/autoit3/docs/functions/FileWriteLine.htm . It appears you can leave off the & #CRLF in your FileWriteLine command.
AutoIt should use the same line terminator that is read in, or
"If the line does NOT end in #CR or #LF then a DOS linefeed (#CRLF)
will be automatically added."
Here's the solution I came up. It works, but I'm not sure it's the cleanest.
Opt("MustDeclareVars", 1) ;0 = no, 1 = require pre-declare
#include <File.au3>
#include <Array.au3>
Local $gInPath = $CmdLine[1]
Local $NumberOfLines = $CmdLine[2]
Local $gInDrive, $gInDir, $gInFName, $gInExt, $gOutPath
Local $gMsgBoxTitle = "Error in " & #ScriptName
Local $InLine
Local $LineCount
Local $oFileIn
Local $oFileOut
Local $FileStringAppend
Local Const $CHAR_READ_BLOCK = 100
Local $CharsRead = 0
Local $CrFound = 0
Local $LfFound = 0
Local $Newline
Local $InBlock
If FileExists($gInPath) Then
Else
MsgBox(4096, $gMsgBoxTitle, "This file does not exist" & #CRLF & $gInPath)
Exit
EndIf
_PathSplit($gInPath, $gInDrive, $gInDir, $gInFName, $gInExt)
If $NumberOfLines >= 1000000 Then
$FileStringAppend = $NumberOfLines / 1000000 & "M"
ElseIf $NumberOfLines >= 1000 Then
$FileStringAppend = $NumberOfLines / 1000 & "K"
Else
$FileStringAppend = $NumberOfLines
EndIf
$gOutPath = _PathMake($gInDrive, $gInDir, $gInFName & "_" & $FileStringAppend, $gInExt)
If FileExists($gOutPath) Then
MsgBox(4096, $gMsgBoxTitle, "File already exists" & #CRLF & $gOutPath)
Exit
EndIf
$oFileIn = FileOpen($gInPath, 0)
$oFileOut = FileOpen($gOutPath, 1)
; Check if file opened for reading OK
If $oFileIn = -1 Then
MsgBox(4096, $gMsgBoxTitle, "Unable to open file for read" & #CRLF & $gInPath)
Exit
EndIf
; Check if file opened for writing OK
If $oFileOut = -1 Then
MsgBox(4096, $gMsgBoxTitle, "Unable to open file for write." & #CRLF & $gOutPath)
Exit
EndIf
While $CrFound = 0 And $LfFound = 0
$CharsRead += $CHAR_READ_BLOCK
$InBlock = FileRead($oFileIn, $CharsRead)
If StringRight($InBlock, 1) = #CR Then
$InBlock = $InBlock & FileRead($oFileIn, $CharsRead)
EndIf
$CrFound = StringInStr($InBlock, #CR)
$LfFound = StringInStr($InBlock, #LF)
If $CrFound > 0 And $LfFound > 0 Then
$Newline = #CRLF
ElseIf $CrFound > 0 Then
$Newline = #CR
Else
$Newline = #LF
EndIf
WEnd
; Read first line of text
$InLine = FileReadLine($oFileIn, 1)
$LineCount = 1
FileWriteLine($oFileOut, $InLine & $Newline)
; Read in lines of text until the EOF is reached
While 1
$InLine = FileReadLine($oFileIn)
$LineCount += 1
If #error = -1 Then ExitLoop
If $LineCount > $NumberOfLines Then ExitLoop
FileWriteLine($oFileOut, $InLine & $Newline)
WEnd
FileClose($oFileIn)
FileClose($oFileOut)

Post File name variable using tcpsend autoit

I need to know how to post file name variable to desired one instead of "upload.zip"
i know how to automate file name using php only but required autoit to post variable of file name using tcpsend method
Thanks
PHP code:
<?php
print_r($_POST);
print_r($_FILES);
copy($_FILES["upload"]["tmp_name"], "upload.zip");
?>
Autoit code:
ConsoleWrite(_PHPupload('192.168.1.2', _OSmacros(), 89, '/upload/index.php', 'application/zip') & #CRLF)
Func _PHPupload($pIP, $pMacros, $pPort, $phpPath, $pContent)
If FileExists($pFile) = 0 Then Return SetError(1, 1, '')
$pTcpc = TCPConnect($pIP, $pPort)
If #error Then Return SetError(1, 2, '')
Local $pBound = "-----" & Random(10000000, 99999999, 1)
Local $pData1 = "--" & $pBound & #CRLF
$pData1 &= 'Content-Disposition: form-data; name="upload"; filename="' & $pFile & '"' & #CRLF & 'Content-Type: ' & $pContent & #CRLF & #CRLF
Local $pData2 = #CRLF & "--" & $pBound & #CRLF & 'Content-Disposition: form-data ;name="test"' & #CRLF & #CRLF & "variable" & #CRLF
$pData2 &= "--" & $pBound & "--" & #CRLF & #CRLF
Local $pHeader = 'POST ' & $phpPath & ' HTTP/1.1' & #CRLF
$pHeader &= 'Host: ' & $pIP & #CRLF
$pHeader &= 'User-Agent: ' & $pMacros & #CRLF
$pHeader &= 'Content-Type: multipart/form-data; boundary=' & $pBound & #CRLF
$pHeader &= 'Content-Length: ' & (StringLen($pData1) + StringLen($pData2) + FileGetSize($pFile)) & #CRLF & #CRLF
Local $pFopen = FileOpen($pFile, $FO_READ)
If $pFopen = -1 Then Return SetError(1, 3, '')
Local $sFread = FileRead($pFopen)
TCPSend($pTcpc, $pHeader & $pData1 & $sFread & $pData2)
If #error Then Return SetError(1, 4, '')
Local $pBuffer = ""
While 1
$pBuffer &= TCPRecv($pTcpc, 1024)
If #error Then
Return SetError(1, 5, '')
Else
ExitLoop
EndIf
WEnd
MsgBox(64, "", $pBuffer)
EndFunc ;==>_PHPupload
$pFile is not declared, but even if it is, it wont work because its a
filepath and you are sending it as a filename at
filename="' & $pFile
This should work:
ConsoleWrite(_PHPupload('192.168.1.2', _OSmacros(), 89, '/upload/index.php', 'application/zip', "c:\somedir", "somefile.zip") & #CRLF)
Func _PHPupload($pIP, $pMacros, $pPort, $phpPath, $pContent, $pFilePath, $pFileName)
$pFile = $pFilePath & "\" & $pFileName
If FileExists($pFile) = 0 Then Return SetError(1, 1, '')
$pTcpc = TCPConnect($pIP, $pPort)
If #error Then Return SetError(1, 2, '')
Local $pBound = "-----" & Random(10000000, 99999999, 1)
Local $pData1 = "--" & $pBound & #CRLF
$pData1 &= 'Content-Disposition: form-data; name="upload"; filename="' & $pFileName & '"' & #CRLF & 'Content-Type: ' & $pContent & #CRLF & #CRLF
Local $pData2 = #CRLF & "--" & $pBound & #CRLF & 'Content-Disposition: form-data ;name="test"' & #CRLF & #CRLF & "variable" & #CRLF
$pData2 &= "--" & $pBound & "--" & #CRLF & #CRLF
Local $pHeader = 'POST ' & $phpPath & ' HTTP/1.1' & #CRLF
$pHeader &= 'Host: ' & $pIP & #CRLF
$pHeader &= 'User-Agent: ' & $pMacros & #CRLF
$pHeader &= 'Content-Type: multipart/form-data; boundary=' & $pBound & #CRLF
$pHeader &= 'Content-Length: ' & (StringLen($pData1) + StringLen($pData2) + FileGetSize($pFile)) & #CRLF & #CRLF
Local $pFopen = FileOpen($pFile, $FO_READ)
If $pFopen = -1 Then Return SetError(1, 3, '')
Local $sFread = FileRead($pFopen)
TCPSend($pTcpc, $pHeader & $pData1 & $sFread & $pData2)
If #error Then Return SetError(1, 4, '')
Local $pBuffer = ""
While 1
$pBuffer &= TCPRecv($pTcpc, 1024)
If #error Then
Return SetError(1, 5, '')
Else
ExitLoop
EndIf
WEnd
MsgBox(64, "", $pBuffer)
EndFunc ;==>_PHPupload

WhoIs servers are not responding

I'm trying to realize a little script in Autoit that retrieves all IPs used by Facebook servers (query "-i origin AS32934" to whois.radb.net, as developer page says), but I don't understand why WhoIs servers are not responding to my queries.
This is the script:
Local $host = "whois.radb.net", $query = "-i origin AS32934"
If Ping($host) Then
$ws = DllOpen("ws2_32.dll")
TCPStartup()
$ip = TCPNameToIP($host)
If #error Then _err("TCPNameToIP", #error)
Global $socket = TCPConnect($ip, 43)
If #error Then _err("TCPConnect", #error)
TCPSend($socket, $query)
If #error Then _err("TCPSend", #error, 1)
Local $text = "", $t = TimerInit(), $counter = 0
While 1
$recv = TCPRecv($socket, 2048)
If #error And #error <> -1 Then
$aRet = DllCall($ws, "int", "WSAGetLastError")
MsgBox(16,"ERROR", "Function: TCPRecv" & #CRLF & "Last data received: " & $recv & #CRLF & "Winsock error: " & $aRet[0] & #CRLF & "Loop executed " & $counter & " times")
ExitLoop
EndIf
$text &= $recv
$counter += 1
If TimerDiff($t) > 4999 Then ExitLoop
WEnd
If $text = "" Then
MsgBox(48, "RESULT", "EMPTY" & #CRLF & "Loop executed " & $counter & " times")
Else
MsgBox(0, "RESULT", $text)
EndIf
TCPCloseSocket($socket)
TCPShutdown()
Else
_err("Ping", #error, 0)
EndIf
Func _err($func, $err, $opt = 2)
MsgBox(16, "ERROR", "Function: " & $func & #CRLF & "Error: " & $err)
If $opt = 1 Then TCPCloseSocket($socket)
If $opt > 0 Then TCPShutdown()
Exit
EndFunc
The output is always "RESULT:EMPTY".
I've tried to query other WhoIs services with various queries (for example whois.verisign-grs.com with "=facebook.com") but I get no response.
It's not a problem about my network, because I've tried a Nirsoft WhoIs tool ad it works.
I've downloaded a sniffer and this is the output when I start my script:
==================================================
Protocol : TCP
Local Address : 192.168.1.101
Remote Address : 198.108.0.18
Local Port : 23509
Remote Port : 43
Remote Host : whois.radb.net
Service Name : nicname
Packets : 5 {5 ; 0}
Data Size : 17 Bytes {17 ; 0}
Total Size : 274 Bytes {217 ; 57}
Data Speed : 0.0 KB/Sec
Capture Time : 07/07/2014 15:18:37:313
Last Packet Time : 07/07/2014 15:18:45:837
Duration : 00:00:08.523
==================================================
Content:
-i origin AS32934
It seems the packet is sent but no packet is received.
I just found out the solution: adding a #crlf at the end of TCPSend() request
$query = "-i origin AS32934" & #crlf

If Then statement in a loop

I'm creating a script that will open a program , login , and do specific tasks .
I created the login script with a variables adding and loopin through .
The problem is with the program , sometimes it just gives you an error on connection or a network problem .
What I need is IF the script gets the problem it'll reset it self and go through the account it got the error on , This is what I have so far and I just can't make it work
$t = 0
$n = "account"
$p = "password"
For $r = X To X
Run("program")
AutoITSetOption("MouseCoordMode", 0)
AutoITSetOption("WinTitleMatchMode", 3)
Do
Sleep(1000)
$t = $t + 1
Until WinActive("program") Or $t = 15
$t = 0
Sleep(1500)
Send("{TAB}")
Sleep(100)
Send("{TAB}")
Sleep(100)
Send("{Enter}")
Sleep(100)
Send($n & $r)
Sleep(200)
Send("{TAB}")
Sleep(200)
Send($p & $r)
Sleep(100)
Send("{Enter}")
Sleep(5500)
If $t > 14 Then
$r = $r - 1
Run(#ComSpec & " /c taskkill /F /im program.exe")
Do
Sleep(500)
$t = $t + 1
Until WinActive("Program - Update News") Or $t = 15
$t = 0
WinActivate("Program")
Sleep(2000)
MouseClick("Primary", 28, 12)
Sleep(1000)
MouseClick("Primary", 35, 125)
Sleep(1000)
MouseClick("Primary", 360, 175)
Sleep(2000)
Send("{ENTER}")
Sleep(2500)
Run(#ComSpec & " /c taskkill /F /im program.exe")
; EndIf
Next
Right now what it does is reruns the program without actually closing the error window
Hopefully this will give you a better idea of how to create a script and fix your problem. It is commented to give you an understanding of the steps taken.
#include <msgboxconstants.au3>
Local $t = 0, $n = "account", $p = "password" ; $n & $p are your own data
Local $r = ["X", "X", "X"], $e, $msg, $w ;$r is filled with your own data
AutoItSetOption("MouseCoordMode", 0)
AutoItSetOption("WinTitleMatchMode", 3)
HotKeySet("{ESC}", "Quit") ;If you want to exit the script, press the ESC key
Sender() ;call the function to run
While 1
If $e <> 0 Then ;if #error is set to a non-zero variable, wait 1 sec (1000 millisec) and run again
Sleep(1000)
Sender()
ElseIf $w = 0 Then ;if msgbox value is 0 AND retry OR ignore has been pressed, wait 1 second and run again
Sleep(1000)
$w += 1
Sender()
EndIf
WEnd
Func Sender() ;wrapped in function to make returning out of the function easier
For $r = "X" To UBound($r) ; for the first value in $r to the length of the array
Run("program")
$e = #error ;if Run sets #error then put #error and check the value with an if statement
If $e <> 0 Then
$msg = MsgBox(2, "ERROR", "error running program, exiting...")
If $msg = $IDABORT Then ;if we don't want to run the program again we abort
Quit()
ElseIf $msg = $IDRETRY Then ;if we want to retry then we hit retry
Return
ElseIf $msg = $IDIGNORE Then ;if we want to retry then we hit ignore as well
Return ;go out of the function because we have recieved an error and want to restart the function
EndIf
EndIf
SetError(0) ;sets #error to 0 so that we don't accidentally restart our program
Do
Sleep(1000)
$t += 1 ;add 1 to $t
Sleep(1500)
Send("{TAB}")
Sleep(100)
Send("{TAB}")
Sleep(100)
Send("{Enter}")
Sleep(100)
Send($n & $r)
Sleep(200)
Send("{TAB}")
Sleep(200)
Send($p & $r)
Sleep(100)
Send("{Enter}")
Sleep(5500)
If $t > 14 Then
$r -= 1 ;minus 1 from $r
Run(#ComSpec & " /c taskkill /F /im program.exe")
$e = #error
If $e <> 0 Then
$msg = MsgBox(2, "ERROR", "error running " & #ComSpec & " /c taskkill /F /im program.exe, Abort to Quit; Retry & Ignore to RETRY.")
If $msg = $IDABORT Then
Quit()
ElseIf $msg = $IDRETRY Then
Return
ElseIf $msg = $IDIGNORE Then
Return
EndIf
EndIf
EndIf
SetError(0)
Until WinActive("program") Or $t = 15
$t = 0 ;set $t to 0
Do
Sleep(500)
$t += 1
$w = WinActivate("Program")
If $w = 0 Then
$msg = MsgBox(2, "ERROR", "error activating program, Abort to Quit; Retry & Ignore to RETRY.")
If $msg = $IDABORT Then
Quit()
ElseIf $msg = $IDRETRY Then
Return
ElseIf $msg = $IDIGNORE Then
Return
EndIf
EndIf
$w += 1
Sleep(2000)
MouseClick("Primary", 28, 12)
Sleep(1000)
MouseClick("Primary", 35, 125)
Sleep(1000)
MouseClick("Primary", 360, 175)
Sleep(2000)
Send("{ENTER}")
Sleep(2500)
Run(#ComSpec & " /c taskkill /F /im program.exe")
$e = #error
If $e <> 0 Then
$msg = MsgBox(2, "ERROR", "error running " & #ComSpec & " /c taskkill /F /im program.exe, Abort to Quit; Retry & Ignore to RETRY.")
If $msg = $IDABORT Then
Quit()
ElseIf $msg = $IDRETRY Then
Return
ElseIf $msg = $IDIGNORE Then
Return
EndIf
EndIf
SetError(0)
Until WinActive("Program - Update News") Or $t = 15
Next
EndFunc ;==>Sender
Func Quit() ;will be called when we want to completely stop the script
Exit
EndFunc ;==>Quit

Resources