Jump to content
boomingranny

AutoIt ConsoleWrite (using "builtin" Autoit Hidden window)

Recommended Posts

Use this UDF to add a console gui to your script (with log file):
It uses the Hidden Autoit window (that you probably didn't even know existed)
Closing Console window will terminate script.

example of console:
image.png.81c28af5c81bbd9fa3b8c5ad8cee9b04.png

#include-once
#include <GuiEdit.au3>

EnableConsoleGui("example.log")

;example:
;------------------------
ConsoleWrite ("Hello World")
For $i = 1 To 10
    ConsoleWrite (".")
    Sleep(200)
Next
ConsoleWrite ("done")
ConsoleWrite(@CRLF)
ConsoleWrite ("close me to exit"&@CRLF)
While 1
    Sleep(1000)
WEnd

;------------------------
;end of example code

Func EnableConsoleGui($Logfile="")
    ;EnableConsoleGUI
    ;by Daniel Barnes 20/04/2018
    ;Uses AutoIt's Hidden window as a console (output only)

    Global $pidChild

    ;if we don't have a parent (as the parent window would have our script name)
    If Not WinExists(StringTrimRight(@ScriptName,4)) Then

        Opt("TrayIconHide",1)

        ;get Autoit's hidden window handle
        local $hWnd = WinGetHandle(AutoItWinGetTitle())

        ;move the autoit hidden window to the middle of the screen
        WinMove($hWnd, "", (@DesktopWidth / 2) - 250, (@DesktopHeight / 2) - 250, 500, 500)

        ;get the Handle of the edit box in Autoit's hidden window
        $hEditBox = ControlGetHandle($hWnd,"","[CLASS:Edit; INSTANCE:1]")

        ;show it
        WinSetState($hWnd, "", @SW_SHOW)

        ;set its title = our script name
        WinSetTitle($hWnd,"",StringTrimRight(@ScriptName,4))

        ;Spawn a child "copy" of the script, enabling reading of its console...
        If @Compiled Then
            ;2 = $STDOUT_CHILD. This avoids requiring the AutoItConstants.au3 in this sample code
            $pidChild= Run( FileGetShortName(@ScriptFullPath),@ScriptDir,"",2)
        Else
            ;2 = $STDOUT_CHILD. This avoids requiring the AutoItConstants.au3 in this sample code
            $pidChild= Run( FileGetShortName(@AutoItExe) & " " & FileGetShortName(@ScriptFullPath),@ScriptDir,"",2)
        EndIf

        OnAutoItExitRegister("EnableConsoleGui_CloseChildPID")

        ;read the console, while the child window exists (and the console window is visible)
        While ProcessExists($pidChild)
            $ConsoleRead = StdoutRead($pidChild)
            If $ConsoleRead then
                $text = StringLeft(ControlGetText($hWnd,"",$hEditBox),65535)
                If $Logfile Then FileWrite($Logfile,$ConsoleRead)
                $text &= $ConsoleRead
                ControlSetText($hWnd,"",$hEditBox,$text)
                ConsoleWrite($ConsoleRead)
                ;scroll to bottom of console edit window
                _GUICtrlEdit_SetSel($hEditBox, 65535, 65535)
            endif
            Sleep(250)
        WEnd
        exit
    endif
EndFunc

Func EnableConsoleGui_CloseChildPID()
    ;if this func isn't used
    ;when you close the console gui
    ;the child "clone" of your script will keep running
    ProcessClose($pidChild)
EndFunc
Edited by boomingranny

Share this post


Link to post
Share on other sites

Nice idea. I would however rename the internal window first to something unique (like adding the PID) and then get the title.


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

Share this post


Link to post
Share on other sites
On 5/5/2018 at 4:45 AM, Skysnake said:

Would you care to provide a use case?

It is useful if you use ConsoleWrite in your script to debug,
when it is uncompiled you can still use Scite to debug, and when it is compiled (and perhaps on another computer) you can see the ConsoleWrite text on the screen, and later in the log file.

(I know what you might be thinking...you can just compile as a console EXE...that is very true)

The reason I made it was because I read another post about the "AutoIt hidden Window" that, even though I had used AutoIt for years, i had never seen,
Once i saw it I wondered what it was all about and why it had a textbox with no text. So I took it as a challenge...

Share this post


Link to post
Share on other sites
On 4/30/2018 at 11:28 PM, guinness said:

Nice idea. I would however rename the internal window first to something unique (like adding the PID) and then get the title.

Sounds smart!

How do you rename the window before getting its title?
Is there another way to get its handle?

Share this post


Link to post
Share on other sites

@boomingranny check how I do it in 

 


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

Share this post


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

  • Similar Content

    • By Luigi
      Greetings,
      Is possible build a script to send/receive commands in "Native Messagin" ?

      If you install this extension:
      https://chrome.google.com/webstore/detail/native-messaging-example/mefhabneoickhhbiglkmehhmemefkopf/related
      And this complement:
      https://github.com/Mandar-Shinde/Google-Chrome-Native-Messaging/releases/download/V1.0/GoogleNativeClient.exe

      You have a work example to send / receive messages from Google Chrome's plugin and NativeMessagingApp.exe.

      I found the source NativeMessagingApp.exe's here:
      https://github.com/Mandar-Shinde/Google-Chrome-Native-Messaging
      I try build this script... But not work...
       
      #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_Compression=4 #AutoIt3Wrapper_Outfile=C:\Users\Public\GoogleNativeClient\NativeMessagingApp2.exe #AutoIt3Wrapper_UseUpx=y #AutoIt3Wrapper_Change2CUI=y #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** #NoTrayIcon #include-once #include <Array.au3> #include <JSMN.au3> ; https://github.com/chechelaky/AutoIt/blob/master/JSMN.au3 #include <Debug.au3> Global $msg = "@empty" Global Const $CLIENT_START = '{"text":"Client Started"}' Global Const $CLIENT_STOP = '{"text":"Client Stopped"}' Global Const $CLIENT_CLICK = '{"text":"Client Click"}' _DebugSetup("NativeMessagingApp2", True, 4, @ScriptDir & "\NativeMessagingApp2.log", True) Global $read, $json, $out = "" If IsArray($CmdLine) Then ;~ $msg = @LF & "Google Chrome Native Messaging App V1" & @LF & @LF & _ ;~ "GPLV3 software distributed under the License is distributed on an ""AS IS"" BASIS" & @LF & _ ;~ "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied." & @LF & _ ;~ "See the License for the specific language governing permissions and" & @LF & _ ;~ "limitations under the License." & @LF & @LF ;~ Local $size = UBound($CmdLine, 1) - 1 ;~ $msg &= "App running with args=" & $size & @LF ;~ For $ii = 0 To $size ;~ $msg &= $ii & " : " & $CmdLine[$ii] & @LF ;~ Next ;~ _DebugOut($msg) EndIf sendMessage($CLIENT_START) While Sleep(10) $read = ConsoleRead() If @error And $out Then _DebugOut("$read...............: " & $out) $json = Jsmn_decode($out) If @error Then _DebugOut("$json...............: @Error") Else _DebugOut("$json...............: @Ok") EndIf If IsObj($json) And $json.Exists("text") Then sendMessage('{"text":"' & $json.Item("text") & '"}') Else sendMessage('{"text":"@Error"}') EndIf $out = "" Else $out &= $read EndIf WEnd Func sendMessage($var) ConsoleWrite($var & @CRLF) _DebugOut("sendMessage===>" & $var) EndFunc ;==>Say  
      Edit the file:
      C:\Users\Public\GoogleNativeClient\com.google.chrome.example.echo-win.json

      And replace:
      "path": "NativeMessagingApp.exe",
      By:
      "path": "NativeMessagingApp2.exe",
      Then plugin call the AutoIt script...

      But is not functional...

       
      About the file mainwindow.cpp, have this function:
      inline QString sendMessage(QString data){ unsigned int len = data.length(); cout.write(reinterpret_cast<const char *>(&len), 4); cout << data.toUtf8().data() << flush; return ""; } How re-write this to AutoIt?
      How execute a flush?



      Best regards.
    • By Danyfirex
      Hello guys.  It's been awhile since I shared something. So today I want to share my last project.
      What's Loga?
      Loga is a simple logging library to keep track of code with an integrated console.
      Features.
      Common log levels. Integrated console. Multiple instances. Custom color and font for each instance log level. Define output format with macros. Conditional and occasional Logging. Easy to use. Basic Usage:
      #include "..\Loga.au3" ;This are some of the default settings: ;Default log level $LOGA_LEVEL_TRACE ;output format: {Symbol}{LogIndex} {LevelName} {LongDateTime} {Message} ;Log to File is enabled. ;Log file name format: YYYYMMDDHHMM-Loga-InstanceIndex.log ;Custom Console is disabled by default. ;By default log to STDOUT. _LogaTrace("I'm Trace") _LogaDebug("I'm Debug") _LogaInfo("I'm Info") _LogaWarn("I'm Warn") _LogaError("I'm Error") _LogaFatal("I'm Fatal")  
      More examples here.
       
      Check Loga on GitHub.
       
      Loga Latest Release v1.0.2.
       
      Saludos
       
       
       
       
    • By Burgs
      Greetings,
        I would like to be able to write a script to send commands to the console for creation of Gstreamer pipelines.  I was thinking of something similar to this:
      Local $iPID = Run("C:\Windows\System32\cmd", "", @SW_MAXIMIZE) ;THIS OPENS THE CONSOLE...!!! if $iPID == 0 Then ConsoleWrite(@CRLF & "I DID NOT OPEN CMD...error: " & @error & @CRLF) if $iPID <> 0 Then ConsoleWrite(@CRLF & "I OPENED CMD...!!!" & @CRLF) $hCmd = WinGetHandle("C:\WINDOWS\system32\cmd.exe") if $hCmd <> 0 Then WinActivate($hCmd) ;ensure command console is active... $sOutput = Send("cd C:\gstreamer\1.0\x86_64\bin" & @CRLF, $SEND_RAW) $sOutput = Send("gst-launch-1.0 videotestsrc ! autovideosink" & @CRLF, $SEND_RAW) Sleep(3000) ControlSend($hCmd, "", "", "exit" & @CR) EndIf ;$hCmd NOT "0"... I don't really know if this is the best way to open the console and send commands into it.  I'm also not sure about how to best catch any errors that may occur...likely this needs to be accomplished with the STDOUTREAD command however I've not had experience using it before and therefore would appreciate some advice that anybody may offer. 
      Basically I'm seeking guidance on how to best automate the opening of the console, sending lines of commands to be executed, and handling any potential errors in the execution of those commands...I thank you in advance.  Regards.
    • By Jeep
      Here is a small library (UDF) that I use all the time. Not transcendent, it’s just to simplify my life.
      When I use the ConsoleWrite function, more than 99.99 percent, I go to the line (Newline), more than 99.99 %, parameters à the same except information that i exam. _CW is born.
      The second one _CW_Fmt allows to display marks (Fmt for Formatting) and allows to evaluate the format the length of a variable and the position of some characters without counting too much :-).
      For the functions derived from MsgBox () again the same observation, always the same parameters following the context: Info, Error or Warning. Thus were born _MB_Info, _MB_Error and _MB_Warning.
      As for _MB_IsOk, the same observation about the logical answer we are interested in a question with two choices: agree or disagree and not much else (True or False).
      All your remarks, suggestions and constructive criticism are welcome.
      JPD_Simply.au3
      JPD_Simply_Demo.au3
    • By TheAutomator
      A fullscreen console with custom commands!

      Introduction:
      Hi everyone!
      This funny project started as a question in the help section:
      https://www.autoitscript.com/forum/topic/174404-edit-detect-key-before-updating-content/
      I'd like to share this script with everyone that is interested. 
       
      Why would I want it?
      You like the old style fullscreen console (like in the old day's), You can add custom commands, You can customize the font a lot more compared to cmd.exe, You can share ideas or add tweaks to the script.  
      Still to do:
      Write a simple custom programming language to implement this tool. Writing a little help file / pdf to describe my little programming language. Add little sound effects like a beep if there is a syntax error (optional). Clean up and modify Console.Au3 content. Add an option to have to type a login password (optional). Make an optional installer that also gives scripts for this tool a custom icon and open with command. ...Call Neo?  
      Thanks to:
      xxaviarxx: debugging, some ideas. jguinch: debugging, adding a bunch of tweaks and ideas. kylomas: debugging, new ideas.  
      Edits and updates:
      Added usage of tab key in edit control Edit has focus now on startup I'm currently rewriting a simple custom programming language to implement this tool.  
      UDF download: Console.au3
       
      Regards
      TheAutomator
×
×
  • Create New...