#include-once

#include <WinAPIProc.au3>


; Written by "Domi78".  If you modify or use it, please let my credits there (as i left the credits to cbruce).
; Use this syntax:  Output("data")     (It is the same syntax as the ConsoleWrite-function, but is yet not tested with binary data)
; Thanks to the post from "cbruce":  https://www.autoitscript.com/forum/topic/189553-writing-to-cmd/?do=findComment&comment=1361142

Global $bOutputCMD = False
Global $bOutputFile = False
Global $bOutputMsgBox = False
Global $bOutputEditor = True
Global $hOutputConsole = 0
Local Const $sLogFile = @ScriptDir & "\" & @ScriptName & ".log"


For $i = 1 To $CmdLine[0]

   If $CmdLine[$i] = "/?" Or $CmdLine[$i] = "/help" Then
      Local $sString = "Use one (or more) of the following options:" & @CRLF & @CRLF
      $sString &= "/?  /help" & @TAB & "Shows this help window and continues the program." & @CRLF
      $sString &= "/cmd" & @TAB & "Redirect the output to the command window." & @CRLF
      $sString &= "/file" & @TAB & "Redirect the output to a logfile in the current directory." & @CRLF
      $sString &= "/msgbox" & @TAB & "Redirect every output to a new message box." & @CRLF
      $sString &= "/noscite" & @TAB & "Don't write to the editor output window via ""Output()""-Call." & @CRLF
      MsgBox(0, "AutoIt3 Output", $sString)
   EndIf

   If $CmdLine[$i] = "/noscite" Then $bOutputEditor = False
   If $CmdLine[$i] = "/msgbox" Then $bOutputMsgBox = True
   If $CmdLine[$i] = "/file" Then
      $bOutputFile = True
	  FileWriteLine($sLogFile, @CRLF & "  " & @YEAR&"-"&@MON&"-"&@MDAY & " " & @HOUR&":"&@MIN&":"&@SEC & ")  Starting Logging...")
   EndIf
   If $CmdLine[$i] = "/cmd" Then
      $bOutputCMD = True
      AutoItSetOption("TrayIconHide", 1)
      _WinAPI_AttachConsole()
      $hOutputConsole = _WinAPI_GetStdHandle(1)
   EndIf

Next


Func Output($sString = "")
   If $bOutputEditor = True Then  ConsoleWrite($sString)
   If $bOutputMsgBox = True Then  MsgBox(64+4096, "AutoIt3 Output", $sString)
   If $bOutputFile = True Then    FileWrite($sLogFile, $sString)
   If $bOutputCMD = True Then     _WinAPI_WriteConsole($hOutputConsole, $sString)
EndFunc
