Jump to content

Help Using WinActive with a Changing window title


driverj
 Share

Recommended Posts

Hello, Long time browser, first time poster

 

I can usually find everything I need by searching, but this time I seem to be falling short

I have been working on some code to use with UltraVNC to log in as a specific user.  I know... discrepancies.... but humor me and help me get this code working.  I would like to be lazy rather than touch many many many machines manually.  I know there will be times when the machine is logged in, but I plan to reboot them via Wake on Lan before issuing these commands!

 

I want AutoIT to launch the VNC window and wait for the window to be active, then if the window is active put in a username and password.

Otherwise I want it to close that window and move on to the next.  The problem is with the window name.  The title of the window is something like this:

CN100-123 ( 12.34.56.78 ) - service mode

in this example CN100-123 will be supplied from a csv file as $CR.  the IP Address in parenthesis will change for every machine, so how do i code for this?

I was hoping to be able to use the $CR since it will already have the computer name, but the window is not found and nothing happens.  I left a sleep command commented out and if the window isn't the failure window, it should automatically put in the username and password, but I do not like this, I would rather wait for the correct window and input the information if possible.

 

I have a spiffed up version of this code that pulls the computer names from a CSV file.  The code seems to work, but I didn't code in for an instance when the connection fails, so I am attempting to do so with a very played down and basic version of that code.

here is the code: 

;Computer name Will be pulled from CSV file later
$CR = 'COMPUTERNAME'
;Command to be executed calling UltraVNC using Comptuer name and supplying VNC password
$command = @ProgramFilesDir & "\UltraVNC\vncviewer.exe -connect " & $CR & " -password VNCPASSWORD"

Local $iPID = run($command)
   ;Sleep(20000)
   $stillLooking = True
      While $stillLooking
         $activeWindowTitle = WinGetTitle(WinActive(""))
         ;I want to find the window that is open for this instance
         If $activeWindowTitle == $CR Then
            ;Send Username
            Send("USERNAME")
            Send("{tab}")
            ; Wait for 1 second
            Sleep(1000)
            ;Send Password
            Send("PASSWORD")
            Send("{enter}")
            ; Wait for 2 seconds
            Sleep(2000)
            ;Close the window after typing username and password
            Send("!+{F4}")
            $stillLooking = False
            ;But what if the computer is offline and not responding?   Close and move on!
         ElseIf $activeWindowTitle == "VncViewer Message Box" Then
            ;Closes open dialogue
            Send("{space}")
            $stillLooking = False
            ;done with If statement
         EndIf
            sleep(5)
      WEnd

 

I appreciate any help you can offer!

Thank you in advance!

Link to comment
Share on other sites

WinGetTitle("[REGEXPTITLE:(CN100-\d{1,3} \( \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} \))]")

https://www.autoitscript.com/autoit3/docs/intro/windowsadvanced.htm

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

Link to comment
Share on other sites

36 minutes ago, MuffinMan said:

Have you tried setting WinTitleMatchMode?

And maybe try using a single "=" here:

If $activeWindowTitle == $CR Then

 

Yes I have tried using different forms of the WinTitleMatchMode but I was not having any luck.

I also tried variants of the

If $activeWindowTitle == $CR Then

and 

If $activeWindowTitle = $CR Then

Neither had any affect at all.

 

33 minutes ago, mLipok said:
WinGetTitle("[REGEXPTITLE:(CN100-\d{1,3} \( \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} \))]")

https://www.autoitscript.com/autoit3/docs/intro/windowsadvanced.htm

I will have to dig deeper into this when I have time a Simple copy and paste did not work (of course I edited the CN100- bit to match a real machine leaving off the end portion for the script to finish it, but I am out of time today to really troubleshoot it.)

 

Thank you both for your replies I will be working more on this the rest of the week.

Link to comment
Share on other sites

On 11/15/2016 at 2:59 PM, mLipok said:
WinGetTitle("[REGEXPTITLE:(CN100-\d{1,3} \( \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} \))]")

https://www.autoitscript.com/autoit3/docs/intro/windowsadvanced.htm

 

I ended up using a variant of your suggestion 

WinGetTitle("[REGEXPTITLE:( " & $RowCounter & " \( \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} \))]")

 

This is now working perfectly, when it is ran for a one at a time instance, thank you!

Thank you so much for your help!

Working code:

Added some Log Tracking and log file, Fixed some windows close issues, Looking into Functions now.

 

This is the complete code I am working with in case anyone has ideas while I fiddle with it,

#include <array.au3>
#include <file.au3>
#include <constants.au3>

Global $command= 0
Global $command2= 0
Global $command3= 0

Dim $oneDarray
;CSV File of computers to connect to
_FileReadToArray("PATH:\TO\CSVFILE.csv", $oneDarray,$FRTA_NOCOUNT)
;Play sound bite at start of script
SoundPlay("PATH:\TO\start.wav", 1)
;include script compiled to exe that will Close the Authentication Rejection, runs in background
Local $iPID = Run("PATH:\TO\CAR.exe", "", @SW_SHOWMINIMIZED)
For $y =0 To UBound($oneDarray) -1
   $columnsCounter = stringsplit($oneDarray[$y],",")
   For $x= 1 To UBound($columnsCounter)-1
      Dim $RowCounter=$columnsCounter[$x]
         ;save code space added variable to house the launch command.
         $command= @ProgramFilesDir & "\UltraVNC\vncviewer.exe -connect " & $RowCounter & " -password ULTRAVNCPASSWORD"
         ;save code space added variable to hold code for window selection.
         $ultraVNC= "[REGEXPTITLE:( " & $RowCounter &" \( \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} \))]"
            Local $iPID = run($command)
               $stillLooking = True
                  While $stillLooking
                     $activeWindowTitle = WinGetTitle($ultraVNC)
                     ;I want to find the window that is open for this instance, sleep for 6 seconds if no response
                     ;it's okay to close the window or enter credentials.
                     sleep(3000)
                     ;If the window is found, run the log in part.
                     If StringinStr(WinGetTitle("[ACTIVE]"),"- service mode") Then
                           Send("WINDOWSUSERNAME")
                           Send("{tab}")
                           Sleep(1000)
                           Send("WIDNOWSPASSWORD")
                           Send("{enter}")
                           Sleep(2000)
                        $stillLooking = False
                        ;But what if the computer is offline and not responding?   Close and move on!
                     Else
                        ;Closes open dialogue window
                        Send("{space}")
                        $stillLooking = False
                        ;done with If statement
                     EndIf
                        sleep(1000)
                  WEnd
   Next
Next
$command2= "taskkill /F /IM vncviewer.exe"
$command3= "taskkill /F /IM CAR.exe"
;Close open UltraVNC Windows
Local $iPID = run($command2)
;Close CAR.exe
Local $iPID = run($command3)
sleep(2000)
;Sound bite at end of script to indicate completion
SoundPlay("PATH:\TO\finished.wav", 1)
   ;Messagebox at end of script to indicate completion
   MsgBox(0, "Completed", "Job Finished, Check log file for Errors!")

 

CAR.exe

#include <Date.au3> ;needed for Date and Time
#include <MsgBoxConstants.au3> ;needed for messageboxes
#include <String.au3> ;needed for StringBetween
#include <File.au3>;needed for FileWriteFromArray

;file paths
Global $sFilePath = "PATH:\TO\Log.txt"
Global $sTempFile = "PATH:\TO\CaughtMachines.txt"

;error messages
Global $eTempFile = "An error occurred while writing to temp file."
Global $ErrorLog = "Error Log " & _NowDate() & ":" & @CRLF

;set hotkey for termination
HotKeySet("+!c","Terminate") ; Shift+Alt+c

;counters for errors
Global $w=0 ;connection issue
Global $u=0 ;rejected authentication

$stillLooking = True
   While $stillLooking
      If WinActive("VncViewer Message Box","rejected") then
         Call("RejectedLog")
   ElseIf WinActive("VncViewer Message Box","Failed") then
         Call("FailedLog")
      EndIf
   WEnd

Func RejectedLog()
;rejected Authentication

         ;retrieve the window text of the active window.
         Local $sText = WinGetText("VNC Viewer Status for")
         ;look for text matching machine name
         Local $sString = _StringBetween($sText, "VNC Server:", "Status:")
         ;if it exists and is an array then write the name to a temp file
            If IsArray($sString) Then
               Local $newString = StringReplace($sString[0],"" ,"")
               $PathToYourFileInclusiveName = $sTempFile
               _FileWriteFromArray($PathToYourFileInclusiveName, $sString)
               ;log the temp file to a variable
            Local $RowCounter = FileRead($sTempFile)

         ;close the open window
      ControlClick("VncViewer Message Box","","[CLASS:Button; INSTANCE:1]", "left")
      $stillLooking = True ;True to keep looking for windows, False to close after window has been found and call again when needed
                        ;add one to the log tracker
                        $w = $w +1
                        ;check to see if log file exists, if not, create it and add Error Log title, otherwise open and write to the file
                        If Not FileExists($sFilePath) then
                           FileWrite($sFilePath, $ErrorLog)
                              Local $hFileOpen = FileOpen($sFilePath, $FO_APPEND)
                                 If $hFileOpen = -1 Then
                                    MsgBox($MB_SYSTEMMODAL, "", $eTempFile)
                                    Return False
                                 EndIf
                           ;writes to log file including variable from above for computer name
                           FileWriteLine($hFileOpen, _NowDate() & " " & _NowTime() & " - " & "Authentication rejected - " & $RowCounter)
                           Else
                        ;create a log file to write to
                        If Not FileWrite($sFilePath, "") Then
                           MsgBox($MB_SYSTEMMODAL, "", $eTempFile)
                           Return False
                        EndIf
                        ;opens log file
                        Local $hFileOpen = FileOpen($SFilePath, $FO_APPEND)
                           If $hFileOpen = -1 Then
                              MsgBox($MB_SYSTEMMODAL, "", $eTempFile)
                              Return False
                           EndIf
                        ;writes to log file including variable from above for computer name
                        FileWriteLine($hFileOpen, _NowDate() & " " & _NowTime() & " - " & "Authentication rejected - " & $RowCounter)

                        ;close the log file
                        FileClose($hFileOpen)
                        EndIf
      EndIf
      sleep(1000)
EndFunc

Func FailedLog()
;conection issue

         ;retrieve the window text of the active window.
         Local $sText = WinGetText("VNC Viewer Status for")
         ;look for text matching machine name
         Local $sString = _StringBetween($sText, "VNC Server:", "Status:")
         ;if it exists and is an array then write the name to a temp file
            If IsArray($sString) Then
               Local $newString = StringReplace($sString[0],"" ,"")
               $PathToYourFileInclusiveName = $sTempFile
               _FileWriteFromArray($PathToYourFileInclusiveName, $sString)
               ;log the temp file to a variable
            Local $RowCounter = FileRead($sTempFile)

         ;close the open window
      ControlClick("VncViewer Message Box","","[CLASS:Button; INSTANCE:1]", "left")
      $stillLooking = True ;True to keep looking for windows, False to close after window has been found and call again when needed
                        ;add one to the log tracker
                        $u = $u +1
                        ;check to see if log file exists, if not, create it and add Error Log title, otherwise open and write to the file
                        If Not FileExists($sFilePath) then
                           FileWrite($sFilePath, $ErrorLog)
                              Local $hFileOpen = FileOpen($sFilePath, $FO_APPEND)
                                 If $hFileOpen = -1 Then
                                    MsgBox($MB_SYSTEMMODAL, "", $eTempFile)
                                    Return False
                                 EndIf
                           ;writes to log file including variable from above for computer name
                           FileWriteLine($hFileOpen, _NowDate() & " " & _NowTime() & " - " & "Connectivity issue - " & $RowCounter)
                           Else
                        ;create a log file to write to
                        If Not FileWrite($sFilePath, "") Then
                           MsgBox($MB_SYSTEMMODAL, "", $eTempFile)
                           Return False
                        EndIf
                        ;opens log file
                        Local $hFileOpen = FileOpen($SFilePath, $FO_APPEND)
                           If $hFileOpen = -1 Then
                              MsgBox($MB_SYSTEMMODAL, "", $eTempFile)
                              Return False
                           EndIf
                        ;writes to log file including variable from above for computer name
                        FileWriteLine($hFileOpen, _NowDate() & " " & _NowTime() & " - " & "Connectivity issue - " & $RowCounter)

                        ;close the log file
                        FileClose($hFileOpen)
                        EndIf
      EndIf
      sleep(1000)
EndFunc   

Func Terminate()
   ;end the $stillLooking
   $stillLooking = False
   Exit
EndFunc ;Terminate the task

 

I'm sure there are some checks I am missing, and I plan to add an error log/tracker at some point as well.

 

Thanks again for all your help!

Edited by driverj
updated script, included extras, changed some error logging, added check to see if file exists, converted to functions
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...