;-- TIME_STAMP   2019-03-06 22:01:40   v 0.1

#cs
	Put the following two lines in your Script to use CMD-Funtions:

	#include <Console.au3>
	; These two lines, if the existing Console should be used, if possible
	#AutoIt3Wrapper_Change2CUI=y
	Global Const $_Console_USEWINDOW = True
	; This line, if always a new Console should be created:
	;~ 		Global Const $_Console_USEWINDOW = False

#ce

#include-once
#include <WinAPI.au3>
ConsoleWrite('! Beep ;-)' & @CRLF)

Global $GLOBAL_hConsole, $GLOBAL_hConsoleIn, $CMD_INFINITE = 0xFFFFFFFF
; Initialize the CMD Funcs
; Parameter: [Opt] $ExitOnFatal - If True, The App exits with Fatal error if an error occurs in this Function (Default: False)
; Return values: Success: 1
;                          Error: 0 and @error:
;                                    1 - Could not allocate Console -> no In or outuput-Handle
;                                    2 - GetStdHandle for Output failed -> No Output-Handle, too
;                                    3 - GetStdHandle for Input failed, but we have an Ouput-Handle
;Author: Prog@ndy
Func _Console_STARTUP($ExitOnFatal = 0)
	Local $iPID, $iAttachConsole, $vRet, $hWnd
	If Not @Compiled Then
		If Not IsDeclared("_Console_USEWINDOW") Then
			;MsgBox features: Title=Yes, Text=Yes, Buttons=Yes and No, Default Button=Second, Icon=Critical
			If 6 = MsgBox(276, "No Console App specified!", "You hav to copy these lines to your main-Script, just before you call _Console_STARTUP:" & @CRLF & "; These two lines, if the CMD-Console should be used, if possible" & @CRLF & "	#AutoIt3Wrapper_Change2CUI=y" & @CRLF & "	Global $_Console_USEWINDOW = True" & @CRLF & "; This line, if always a new Console should be created:" & @CRLF & "	Global $_Console_USEWINDOW = False" & @CRLF & @CRLF & "		COPY TO CLIPBOARD?") Then
				ClipPut("; These two lines, if the CMD-Console should be used, if possible" & @CRLF & _
						"#AutoIt3Wrapper_Change2CUI=y" & @CRLF & _
						"Global Const $_Console_USEWINDOW = True" & @CRLF & _
						"; This line, if always a new Console should be created:" & @CRLF & _
						";~ Global Const $_Console_USEWINDOW = False")
			EndIf
		EndIf
		MsgBox(16, 'Console UDF error', "Console does not work in uncompiled scripts.")
		Exit
	EndIf
	If Not IsDeclared("_Console_USEWINDOW") Then Local $_Console_USEWINDOW = True
	If $_Console_USEWINDOW Then
		$vRet = DllCall("Kernel32.dll", "int", "FreeConsole")
		$iPID = WinGetProcess(WinGetHandle(StringFormat('[CLASS:ConsoleWindowClass; REGEXPTITLE:.*%s.*]', StringReplace(@ScriptFullPath, '\', '\\'))))
		$iAttachConsole = _WinAPI_AttachConsole($iPID)
		_ErrorExit($iAttachConsole, $ExitOnFatal, '$iAttachConsole')
;~ 		If Not $iAttachConsole Then $ExitOnFatal ? _WinAPI_FatalAppExit("Could not allocate Console") : Return SetError(2, 0, 0)
	Else
		$vRet = DllCall("Kernel32.dll", "long", "AllocConsole")
		_ErrorExit(@error ? 0 : $vRet[0], $ExitOnFatal, 'AllocConsole')
;~ 		If @error Or $vRet[0] = 0 Then $ExitOnFatal ? _WinAPI_FatalAppExit("Could not allocate Console") : Return SetError(1, 0, 0)
	EndIf
	$hWnd = DllCall("kernel32.dll", "hwnd", "GetConsoleWindow")
	WinSetState($hWnd[0], "", @SW_SHOW)

	$GLOBAL_hConsole = _WinAPI_GetStdHandle(1) ; 0, 1, 2 = input, outout, error
	_ErrorExit($GLOBAL_hConsole > 0, $ExitOnFatal, '_WinAPI_GetStdHandle(1)')
;~ 	If $GLOBAL_hConsole = -1 Then $ExitOnFatal ? _WinAPI_FatalAppExit("Could not allocate Console") : Return SetError(3, 0, 0)
	DllCall("Kernel32.dll", "long", "SetConsoleActiveScreenBuffer", "handle", $GLOBAL_hConsole)
	$GLOBAL_hConsoleIn = _WinAPI_GetStdHandle(0)
	_ErrorExit($GLOBAL_hConsoleIn > 0, $ExitOnFatal, '_WinAPI_GetStdHandle(0)')
;~ 	If $GLOBAL_hConsoleIn = -1 Then $ExitOnFatal ? _WinAPI_FatalAppExit("Could not allocate Console") : Return SetError(4, 0, 0)
	Return 1
EndFunc   ;==>_Console_STARTUP

Func _ErrorExit($vTrue, $ExitOnFatal, $sMsg)
	MsgBox(0, '_ErrorExit', $sMsg & ' $vTrue = ' & $vTrue)
	Return $vTrue ? True : $ExitOnFatal ? _WinAPI_FatalAppExit("Could not allocate Console") : SetError(2, 0, 0)
EndFunc   ;==>_ErrorExit

; PASUES CMD, waits for any key
; Author: ProgAndy
Func _Console_Pause($iTime = -1)
	Local $vRet, $Key_Event = False
	_Console_Write(@CRLF & "PAUSE: Press any key to continue ")
	DllCall("Kernel32.dll", "long", "FlushConsoleInputBuffer", "handle", $GLOBAL_hConsoleIn)
	Local $tInp = DllStructCreate("long;uint64[4]")
	Do
		$vRet = DllCall("Kernel32.dll", "long", "WaitForSingleObject", "handle", $GLOBAL_hConsoleIn, "dword", $iTime)
		If @error Then Return SetError(1, 0, 0)
		If $vRet[0] = -1 Then Return SetError(2, 0, 0)
		Local $rce = DllCall("kernel32.dll", "bool", "ReadConsoleInput", "handle", $GLOBAL_hConsoleIn, "ptr", DllStructGetPtr($tInp), "dword", 1, "dword*", 0)
		$Key_Event = DllStructGetData($tInp, 1) = 1
	Until ($Key_Event And $rce[4]) Or $vRet[0] = 0x00000102
	DllCall("Kernel32.dll", "long", "FlushConsoleInputBuffer", "handle", $GLOBAL_hConsoleIn)
	Return SetExtended($vRet[0] = 0x00000102, 1)
EndFunc   ;==>_Console_Pause

Func _Console_Close()
	Local $vRet = DllCall("Kernel32.dll", "int", "FreeConsole")
	If @error Then Return SetError(1, 0, 0)
	Return SetError($vRet[0] <> 0, 0, $vRet[0])
EndFunc   ;==>_Console_Close

;Writes Text to CMD
; Author: ProgAndy
Func _Console_Write($text)
	Local $temp = _WinAPI_WriteConsole($GLOBAL_hConsole, $text)
	Return SetError(@error, @extended, $temp)
EndFunc   ;==>_Console_Write

;Reads Text from CMD
; Author: ProgAndy
Func _Console_Read($pInputControl = 0)
	Local $tBuffer = DllStructCreate("wchar[4000]")
	Local $aResult = DllCall("Kernel32.dll", "int", "ReadConsoleW", "handle", $GLOBAL_hConsoleIn, "ptr", DllStructGetPtr($tBuffer), "DWORD", 4000, "dword*", 0, "ptr", $pInputControl)
	If @error Then Return SetError(1, @error, "")
	If $aResult[0] = 0 Then Return SetError(2, 0, "")
	Return StringLeft(DllStructGetData($tBuffer, 1), $aResult[4])
EndFunc   ;==>_Console_Read

; Writes the prompt and then reads Text from CMD
; Author: ProgAndy
Func _Console_Ask($sPrompt)
	_Console_Write($sPrompt)
	If @error Then Return SetError(1, @error, "")
	Local $sBuff = _Console_Read()
	If @error Then Return SetError(2, @error, "")
	Return $sBuff
EndFunc   ;==>_Console_Ask

#cs
Console Functions
    Contributors
        Rich Turner Ahmad Ibrahim Matt Wojciakowski Craig Loewen Michael Niksa

The following functions are used to access a console.
	Function                      		Description
	AddConsoleAlias               		Defines a console alias for the specified executable.
	AllocConsole                  		Allocates a new console for the calling process.
	AttachConsole                 		Attaches the calling process to the console of the specified process.
	CreateConsoleScreenBuffer     		Creates a console screen buffer.
	FillConsoleOutputAttribute    		Sets the text and background color attributes for a specified number of character cells.
	FillConsoleOutputCharacter    		Writes a character to the console screen buffer a specified number of times.
	FlushConsoleInputBuffer       		Flushes the console input buffer.
	FreeConsole                   		Detaches the calling process from its console.
	GenerateConsoleCtrlEvent      		Sends a specified signal to a console process group that shares the console associated with the calling process.
	GetConsoleAlias               		Retrieves the specified alias for the specified executable.
	GetConsoleAliases             		Retrieves all defined console aliases for the specified executable.
	GetConsoleAliasesLength       		Returns the size, in bytes, of the buffer needed to store all of the console aliases for the specified executable.
	GetConsoleAliasExes           		Retrieves the names of all executables with console aliases defined.
	GetConsoleAliasExesLength     		Returns the size, in bytes, of the buffer needed to store the names of all executables that have console aliases defined.
	GetConsoleCP                  		Retrieves the input code page used by the console associated with the calling process.
	GetConsoleCursorInfo          		Retrieves information about the size and visibility of the cursor for the specified console screen buffer.
	GetConsoleDisplayMode         		Retrieves the display mode of the current console.
	GetConsoleFontSize            		Retrieves the size of the font used by the specified console screen buffer.
	GetConsoleHistoryInfo         		Retrieves the history settings for the calling process's console.
	GetConsoleMode                		Retrieves the current input mode of a console's input buffer or the current output mode of a console screen buffer.
	GetConsoleOriginalTitle       		Retrieves the original title for the current console window.
	GetConsoleOutputCP            		Retrieves the output code page used by the console associated with the calling process.
	GetConsoleProcessList         		Retrieves a list of the processes attached to the current console.
	GetConsoleScreenBufferInfo    		Retrieves information about the specified console screen buffer.
	GetConsoleScreenBufferInfoEx  		Retrieves extended information about the specified console screen buffer.
	GetConsoleSelectionInfo       		Retrieves information about the current console selection.
	GetConsoleTitle               		Retrieves the title for the current console window.
	GetConsoleWindow              		Retrieves the window handle used by the console associated with the calling process.
	GetCurrentConsoleFont         		Retrieves information about the current console font.
	GetCurrentConsoleFontEx       		Retrieves extended information about the current console font.
	GetLargestConsoleWindowSize   		Retrieves the size of the largest possible console window.
	GetNumberOfConsoleInputEvents 		Retrieves the number of unread input records in the console's input buffer.
	GetNumberOfConsoleMouseButtons		Retrieves the number of buttons on the mouse used by the current console.
	GetStdHandle                  		Retrieves a handle for the standard input, standard output, or standard error device.
	HandlerRoutine                		An application-defined function used with the SetConsoleCtrlHandler function.
	PeekConsoleInput              		Reads data from the specified console input buffer without removing it from the buffer.
	ReadConsole                   		Reads character input from the console input buffer and removes it from the buffer.
	ReadConsoleInput              		Reads data from a console input buffer and removes it from the buffer.
	ReadConsoleOutput             		Reads character and color attribute data from a rectangular block of character cells in a console screen buffer.
	ReadConsoleOutputAttribute    		Copies a specified number of foreground and background color attributes from consecutive cells of a console screen buffer.
	ReadConsoleOutputCharacter    		Copies a number of characters from consecutive cells of a console screen buffer.
	ScrollConsoleScreenBuffer     		Moves a block of data in a screen buffer.
	SetConsoleActiveScreenBuffer  		Sets the specified screen buffer to be the currently displayed console screen buffer.
	SetConsoleCP                  		Sets the input code page used by the console associated with the calling process.
	SetConsoleCtrlHandler         		Adds or removes an application-defined HandlerRoutine from the list of handler functions for the calling process.
	SetConsoleCursorInfo          		Sets the size and visibility of the cursor for the specified console screen buffer.
	SetConsoleCursorPosition      		Sets the cursor position in the specified console screen buffer.
	SetConsoleDisplayMode         		Sets the display mode of the specified console screen buffer.
	SetConsoleHistoryInfo         		Sets the history settings for the calling process's console.
	SetConsoleMode                		Sets the input mode of a console's input buffer or the output mode of a console screen buffer.
	SetConsoleOutputCP            		Sets the output code page used by the console associated with the calling process.
	SetConsoleScreenBufferInfoEx  		Sets extended information about the specified console screen buffer.
	SetConsoleScreenBufferSize    		Changes the size of the specified console screen buffer.
	SetConsoleTextAttribute       		Sets the foreground (text) and background color attributes of characters written to the console screen buffer.
	SetConsoleTitle               		Sets the title for the current console window.
	SetConsoleWindowInfo          		Sets the current size and position of a console screen buffer's window.
	SetCurrentConsoleFontEx       		Sets extended information about the current console font.
	SetStdHandle                  		Sets the handle for the standard input, standard output, or standard error device.
	WriteConsole                  		Writes a character string to a console screen buffer beginning at the current cursor location.
	WriteConsoleInput             		Writes data directly to the console input buffer.
	WriteConsoleOutput            		Writes character and color attribute data to a specified rectangular block of character cells in a console screen buffer.
	WriteConsoleOutputAttribute   		Copies a number of foreground and background color attributes to consecutive cells of a console screen buffer.
	WriteConsoleOutputCharacter   		Copies a number of characters to consecutive cells of a console screen buffer.
#ce
