udflib.Console
;================================================================================================================================
; udflib.console.wbt
; DOS console functions for use with WinBatch 2001 and Windows 98
; Detlev Dalitz.20020216.20020220
;================================================================================================================================


;----------------------------------------------------------------------------------------------------
; udfConAllocConsole ()                                                      ; 2002:02:20:16:53:31
; udfConFreeConsole ()                                                       ; 2002:02:20:16:53:31
; udfConSetConsoleTitle (str)                                                ; 2002:02:20:16:53:31
; udfConGetConsoleTitle ()                                                   ; 2002:02:20:16:53:31
; udfConIsConsoleFullScreen ()                                               ; 2002:02:20:16:53:31
; udfConToggleConsoleState ()                                                ; 2002:02:20:16:53:31
; udfConSetConsoleMode (hConsoleHandle, mode)                                ; 2002:02:20:16:53:31
; udfConGetConsoleMode (hConsoleHandle)                                      ; 2002:02:20:16:53:31
; udfConConsoleExists ()                                                     ; 2002:02:20:16:53:31

; udfConGetHandleStdIn ()                                                    ; 2002:02:20:16:53:31
; udfConGetHandleStdOut ()                                                   ; 2002:02:20:16:53:31
; udfConGetHandleStdErr ()                                                   ; 2002:02:20:16:53:31
; udfCloseHandle (handle)                                                    ; 2002:02:20:16:53:31
; udfConSetStdHandle (StdHandle, HandleToSetAsStd)                           ; 2002:02:20:16:53:31
; udfConSetHandleStdIn (HandleToSetAsStd)                                    ; 2002:02:20:16:53:31
; udfConSetHandleStdOut (HandleToSetAsStd)                                   ; 2002:02:20:16:53:31
; udfConSetHandleStdErr (HandleToSetAsStd)                                   ; 2002:02:20:16:53:31
; udfConIsInputHandle (handle)                                               ; 2002:02:20:16:53:31

; udfConCreateScreenBuffer (DesiredAccess, ShareMode)                        ; 2002:02:20:16:53:31
; udfConSetActiveScreenBuffer (hOutput)                                      ; 2002:02:20:16:53:31
; udfConGetScreenBufferInfo_ (handle, request)                               ; 2002:02:20:16:53:31
; udfConGetScreenBufferInfo (handle, request)                                ; 2002:02:20:16:53:31
; udfConSetScreenBufferSize (hOutput, colx, rowy)                            ; 2002:02:20:16:53:31
; udfConGetMaxWindowSize (handle, mode)                                      ; 2002:02:20:16:53:31
; udfConScrollScreenBuffer (hOutput, stlx, stly, sbrx, sbry, ctlx, ctly, ... ; 2002:02:20:16:53:31
; udfConSetWindowInfo (hOutput, tlx, tly, brx, bry, bAbs)                    ; 2002:02:20:16:53:31
; udfConFillScreenBuffer (hOutput, char, attr)                               ; 2002:02:20:16:53:31

; udfConGetCursorInfo (hOutput)                                              ; 2002:02:20:16:53:31
; udfConSetCursorInfo (hOutput, infostr)                                     ; 2002:02:20:16:53:31
; udfConSetCursorPos (hOutput, colx, rowy)                                   ; 2002:02:20:16:53:31

; udfWriteFile (hOutput, str)                                                ; 2002:02:20:16:53:31
; udfReadFile (hInput)                                                       ; 2002:02:20:16:53:31

; udfConWriteConsole (hOutput, str)                                          ; 2002:02:20:16:53:31
; udfConReadConsole (hInput)                                                 ; 2002:02:20:16:53:31
; udfConFlushInputBuffer (hInput)                                            ; 2002:02:20:16:53:31
; udfConSetTextAttribute (hOutput, attr)                                     ; 2002:02:20:16:53:31
; udfBinaryAllocCharAttrBuf (tlx, tly, brx, bry)                             ; 2002:02:20:16:53:31
; udfBinaryAllocAttrBuf (len)                                                ; 2002:02:20:16:53:31
; udfConReadOutputRegion (hOutput, tlx, tly, brx, bry, bbCharAttr)           ; 2002:02:20:16:53:31
; udfConWriteOutputRegion (hOutput, tlx, tly, brx, bry, bbCharAttr)          ; 2002:02:20:16:53:31
; udfConReadOutputChar (hOutput, colx, rowy, len)                            ; 2002:02:20:16:53:31
; udfConReadOutputAttr (hOutput, colx, rowy, len, bbAttr)                    ; 2002:02:20:16:53:31
; udfConFillOutputChar (hOutput, colx, rowy, len, char)                      ; 2002:02:20:16:53:31
; udfConFillOutputAttr (hOutput, colx, rowy, len, attr)                      ; 2002:02:20:16:53:31
; udfConWriteCharStr (hOutput, colx, rowy, str)                              ; 2002:02:20:16:53:31
; udfConWriteAttr (hOutput, colx, rowy, bbattr)                              ; 2002:02:20:16:53:31

; udfConGetInputCP ()                                                        ; 2002:02:20:16:53:32
; udfConGetOutputCP ()                                                       ; 2002:02:20:16:53:32
; udfConSetInputCP (CodePageID)                                              ; 2002:02:20:16:53:32
; udfConSetOutputCP (CodePageID)                                             ; 2002:02:20:16:53:32

; udfConGetNumberMouseButtons ()                                             ; 2002:02:20:16:53:32

; udfConGetNumberInputEvents (hInput)                                        ; 2002:02:20:16:53:32
; udfConWriteConsoleInput (hInput, bbEvent)                                  ; 2002:02:20:16:53:32
; udfConReadConsoleInput (hInput, bbEvent)                                   ; 2002:02:20:16:53:32
; udfConPeekConsoleInput (hInput, bbEvent)                                   ; 2002:02:20:16:53:32

; udfConGetConsoleWindow ()                                                  ; 2002:02:20:16:53:32
; udfConGetDisplayMode ()                                                    ; 2002:02:20:16:53:32
; udfConSetCtrlHandler (HandlerRoutine, Add)                                 ; 2002:02:20:16:53:32

; udfConRandomFillWindow (hOutput)                                           ; 2002:02:20:16:53:32
; udfConSaveRegionToFile (hOutput, tlx, tly, brx, bry, filename)             ; 2002:02:20:16:53:32
; udfConLoadRegionFromFile (hOutput, tlx, tly, brx, bry, char, attr, ...     ; 2002:02:20:16:53:32
;----------------------------------------------------------------------------------------------------


; ----- CONSTANTS ---------------------------------------------------------------------------------------------------------------
;
;DefineConstant ColorAttributes
FOREGROUND_BLACK        =    0
FOREGROUND_BLUE         =    1
FOREGROUND_GREEN        =    2
FOREGROUND_CYAN         =    3 ; FOREGROUND_GREEN|FOREGROUND_BLUE
FOREGROUND_RED          =    4
FOREGROUND_MAGENTA      =    5 ; FOREGROUND_RED|FOREGROUND_BLUE
FOREGROUND_BROWN        =    6 ; FOREGROUND_RED|FOREGROUND_GREEN
FOREGROUND_LTGRAY       =    7 ; FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE
FOREGROUND_INTENSITY    =    8
BACKGROUND_BLACK        =    0
BACKGROUND_BLUE         =   16
BACKGROUND_GREEN        =   32
BACKGROUND_CYAN         =   48 ; BACKGROUND_GREEN|BACKGROUND_BLUE
BACKGROUND_RED          =   64
BACKGROUND_MAGENTA      =   80 ; BACKGROUND_RED|BACKGROUND_BLUE
BACKGROUND_BROWN        =   96 ; BACKGROUND_RED|BACKGROUND_GREEN|BACKGROUND_BLUE
BACKGROUND_LTGRAY       =  112 ; BACKGROUND_RED|BACKGROUND_GREEN|BACKGROUND_BLUE
BACKGROUND_INTENSITY    =  128

;DefineConstant WinState
CONSOLE_FULLSCREEN = 1
CONSOLE_FULLSCREEN_HARDWARE = 2

;DefineConstant ScreenBuffer
CONSOLE_TEXTMODE_BUFFER   = 1

ENABLE_PROCESSED_INPUT    = 1
ENABLE_LINE_INPUT         = 2
ENABLE_ECHO_INPUT         = 4
ENABLE_WINDOW_INPUT       = 8
ENABLE_MOUSE_INPUT        = 16

ENABLE_PROCESSED_OUTPUT   = 1
ENABLE_WRAP_AT_EOL_OUTPUT = 2

GENERIC_WRITE = 1073741824 ; 2**30
GENERIC_READ  = 2147483648 ; 2**31

FILE_SHARE_READ    = 1
FILE_SHARE_WRITE   = 2
FILE_SHARE_DELETE  = 4

;DefineConstant Handle
STD_INPUT_HANDLE  = -10
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE  = -12
INVALID_HANDLE_VALUE = -1
;
; ----- CONSTANTS ---------------------------------------------------------------------------------------------------------------



; ----- CONSOLE ALLOC FREE TITLE TOGGLE -----------------------------------------------------------------------------------------
;
#DefineFunction udfConAllocConsole ()
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"AllocConsole")
If (result==0) Then result=DllLastError()
Return (result)
; Allocates a new console for the calling process.
#EndFunction

#DefineFunction udfConFreeConsole ()
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"FreeConsole")
If (result==0) Then result=DllLastError()
Return (result)
; Detaches the calling process from its console.
#EndFunction


#DefineFunction udfConSetConsoleTitle (str)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"SetConsoleTitleA",lpstr:str)
If (result==0) Then result=DllLastError()
Return (result)
; Sets the title bar string for the current console window.
#EndFunction


#DefineFunction udfConGetConsoleTitle ()
bbsize = 255
bb = BinaryAlloc(bbsize)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetConsoleTitleA",lpbinary:bb,long:bbsize)
If (result==0)
   result=DllLastError()
Else
   BinaryEodSet(bb,bbsize)
   result = BinaryPeekStr(bb,0,bbsize)
EndIf
BinaryFree(bb)
Return (result)
; Retrieves the title bar string for the current console window.
#EndFunction


#DefineFunction udfConIsConsoleFullScreen ()
title = udfConGetConsoleTitle ()
Return (WinIsDos(title) && (WinState(title)==@ICON))
; maybe a hack ... returns @true if console session is in fullscreen mode
#EndFunction


#DefineFunction udfConToggleConsoleState ()
title = udfConGetConsoleTitle ()
Return(IntControl(22,DllHwnd(title),273,57359,0))
; WM_COMMAND  = 273   ; &H111
; MAGIC_CONSOLE_TOGGLE = 57359 ; 0xE00F
; toggles between fullscreen and window mode, only Win98
; Thanks to Nikolay N. Repin (Nick N. Repin), 1998
; Thanks to 1999 Ashot Oganesyan K, SmartLine, Inc
; mailto:ashot@aha.ru, http://www.protect-me.com, http://www.codepile.com
#EndFunction


#DefineFunction udfConSetConsoleMode (hConsoleHandle, mode)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"SetConsoleMode",long:hConsoleHandle,long:mode)
If (result==0) Then result=DllLastError()
Return (result)
; Sets the input mode of a console's input buffer or the output mode of a console screen buffer.
#EndFunction


#DefineFunction udfConGetConsoleMode (hConsoleHandle)
bb = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetConsoleMode",long:hConsoleHandle,lpbinary:bb)
If (result==0)
   result=DllLastError()
Else
   BinaryEodSet(bb,4)
   result=BinaryPeek4(bb,0)
EndIf
BinaryFree(bb)
Return (result)
; Input handle  ; default=23
; ENABLE_PROCESSED_INPUT    = 1
; ENABLE_LINE_INPUT         = 2
; ENABLE_ECHO_INPUT         = 4
; ENABLE_WINDOW_INPUT       = 8  ; default=off
; ENABLE_MOUSE_INPUT        = 16
;
; Output handle ; default=3
; ENABLE_PROCESSED_OUTPUT   = 1
; ENABLE_WRAP_AT_EOL_OUTPUT = 2
;
; Retrieves the current input mode of a console's input buffer or the current output mode of a console screen buffer.
#EndFunction


#DefineFunction udfConConsoleExists ()
oldmode=ErrorMode(@OFF)
LastError()
handle=FileOpen("conout$","write")
ErrorMode(oldmode)
result=(LastError()<>1077)
If result Then FileClose(handle)
Return (result)
; returns 0..1 resp. @false..@true
#EndFunction
;
; ----- CONSOLE ALLOC FREE TITLE TOGGLE -----------------------------------------------------------------------------------------



; ----- GET SET STDHANDLE -------------------------------------------------------------------------------------------------------
;
#DefineFunction udfConGetHandleStdIn ()
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetStdHandle",long:-10)
If (result==0) Then result=DllLastError()
Return (result)
; STD_INPUT_HANDLE  = -10 ; INVALID_HANDLE_VALUE = -1
; Retrieves a handle for the standard input.
#EndFunction


#DefineFunction udfConGetHandleStdOut ()
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetStdHandle",long:-11)
If (result==0) Then result=DllLastError()
Return (result)
; STD_OUTPUT_HANDLE  = -11 ; INVALID_HANDLE_VALUE = -1
; Retrieves a handle for the standard output.
#EndFunction


#DefineFunction udfConGetHandleStdErr ()
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetStdHandle",long:-12)
If (result==0) Then result=DllLastError()
Return (result)
; STD_ERROR_HANDLE  = -12 ; INVALID_HANDLE_VALUE = -1
; Retrieves a handle for the standard error device.
#EndFunction


#DefineFunction udfCloseHandle (handle)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"CloseHandle",long:handle)
If (result==0) Then result=DllLastError()
Return (result)
#EndFunction


#DefineFunction udfConSetStdHandle (StdHandle, HandleToSetAsStd)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"SetStdHandle",long:StdHandle,long:HandleToSetAsStd)
If (result==0) Then result=DllLastError()
Return (result)
; BOOL SetStdHandle(
;  DWORD nStdHandle,  // input, output, or error device
;  HANDLE hHandle     // handle
; Sets the handle for the standard input, standard output, or standard error device.
#EndFunction


#DefineFunction udfConSetHandleStdIn (HandleToSetAsStd)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"SetStdHandle",long:-10,long:HandleToSetAsStd)
If (result==0) Then result=DllLastError()
Return (result)
; Sets the handle for the standard input.
#EndFunction


#DefineFunction udfConSetHandleStdOut (HandleToSetAsStd)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"SetStdHandle",long:-11,long:HandleToSetAsStd)
If (result==0) Then result=DllLastError()
Return (result)
; Sets the handle for the standard output.
#EndFunction


#DefineFunction udfConSetHandleStdErr (HandleToSetAsStd)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"SetStdHandle",long:-12,long:HandleToSetAsStd)
If (result==0) Then result=DllLastError()
Return (result)
; Sets the handle for the standard error device.
#EndFunction


#DefineFunction udfConIsInputHandle (handle)
bb = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetNumberOfConsoleInputEvents",long:handle,lpbinary:bb)
BinaryFree(bb)
Return (result)
; Is this kind of tricky magic question ok?
; returns 0..1 resp. @false..@true
#EndFunction
;
; ----- GET SET STDHANDLE -------------------------------------------------------------------------------------------------------



; ----- SCREENBUFFER METRICS ----------------------------------------------------------------------------------------------------
;
#DefineFunction udfConCreateScreenBuffer (DesiredAccess, ShareMode)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"CreateConsoleScreenBuffer",long:DesiredAccess,long:ShareMode,lpnull,long:1,lpnull)
If (result==0) Then result=DllLastError()
Return (result)
; dwDesiredAccess;
; GENERIC_WRITE = 1073741824 ; 2**30
; GENERIC_READ  = 2147483648 ; 2**31
; dwShareMode
; FILE_SHARE_READ   = 1
; FILE_SHARE_WRITE  = 2
; FILE_SHARE_DELETE = 4
; lpSecurityAttributes = lpnull;
; dwFlags
; CONSOLE_TEXTMODE_BUFFER = 1
; lpScreenBufferData = lpnull
; INVALID_HANDLE_VALUE = -1
;
; Creates a console screen buffer. Returns a handle.
#EndFunction



#DefineFunction udfConSetActiveScreenBuffer (hOutput)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"SetConsoleActiveScreenBuffer",long:hOutput)
If (result==0) Then result=DllLastError()
Return (result)
; Sets the specified screen buffer to be the currently displayed console screen buffer.
#EndFunction


#DefineFunction udfConGetScreenBufferInfo_ (handle, request)
bb = BinaryAlloc(22)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetConsoleScreenBufferInfo",long:handle,lpbinary:bb)
If (result==0)
   result=DllLastError()
Else
   BinaryEodSet(bb,22)
   result = ""
   Select mode
   Case 0
   Case 1
      result = ItemInsert(BinaryPeek2(bb,0),-1,result,@TAB) ; Screenbuffer Size X
      Continue
   Case 0
   Case 2
      result = ItemInsert(BinaryPeek2(bb,2),-1,result,@TAB) ; Screenbuffer Size Y
      Continue
   Case 0
   Case 3
      result = ItemInsert(BinaryPeek2(bb,4),-1,result,@TAB) ; Cursor Pos X
      Continue
   Case 0
   Case 4
      result = ItemInsert(BinaryPeek2(bb,6),-1,result,@TAB) ; Cursor Pos Y
      Continue
   Case 0
   Case 5
      result = ItemInsert(BinaryPeek2(bb,8),-1,result,@TAB) ; Char Attr
      Continue
   Case 0
   Case 6
      result = ItemInsert(BinaryPeek2(bb,10),-1,result,@TAB) ; Win top left Pos X
      Continue
   Case 0
   Case 7
      result = ItemInsert(BinaryPeek2(bb,12),-1,result,@TAB) ; Win top left  Pos Y
      Continue
   Case 0
   Case 8
      result = ItemInsert(BinaryPeek2(bb,14),-1,result,@TAB) ; Win bottom right Pos X
      Continue
   Case 0
   Case 9
      result = ItemInsert(BinaryPeek2(bb,16),-1,result,@TAB) ; Win bottom right  Pos Y
      Continue
   Case 0
   Case 10
      result = ItemInsert(BinaryPeek2(bb,18),-1,result,@TAB) ; Console Window Max Size X
      Continue
   Case 0
   Case 11
      result = ItemInsert(BinaryPeek2(bb,20),-1,result,@TAB) ; Console Window Max Size Y
      Break
   Case mode
      result = 0
      Break
   EndSelect
EndIf
BinaryFree(bb)
Return (result)
; dwSize
; COORD structure that contains the size, in character columns and rows, of the screen buffer.
; dwCursorPosition
; COORD structure that contains the column and row coordinates of the cursor in the screen buffer.
; wAttributes
; Attributes of the characters written to a screen buffer by the WriteFile and WriteConsole functions,
; or echoed to a screen buffer by the ReadFile and ReadConsole functions.
; For more information, see Character Attributes.
; srWindow
; SMALL_RECT structure that contains the screen buffer coordinates of the display window.
; Left   X-coordinate of the upper left corner of the rectangle.
; Top    Y-coordinate of the upper left corner of the rectangle.
; Right  X-coordinate of the lower right corner of the rectangle.
; Bottom Y-coordinate of the lower right corner of the rectangle.
; dwMaximumWindowSize
; COORD structure that contains the maximum size of the console window,
; given the current screen buffer size and font and the screen size.
;
; Retrieves information about the specified console screen buffer.
#EndFunction


#DefineFunction udfConGetScreenBufferInfo (handle, request)
bb = BinaryAlloc(22)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetConsoleScreenBufferInfo",long:handle,lpbinary:bb)
If (result==0)
   result=DllLastError()
Else
   BinaryEodSet(bb,22)
   Select request
   Case 1
      result = BinaryPeek2(bb,0) ; Screenbuffer Size X
      Break
   Case 2
      result = BinaryPeek2(bb,2) ; Screenbuffer Size Y
      Break
   Case 3
      result = BinaryPeek2(bb,4) ; Cursor Pos X
      Break
   Case 4
      result = BinaryPeek2(bb,6) ; Cursor Pos Y
      Break
   Case 5
      result = BinaryPeek2(bb,8) ; Char Attr
      Break
   Case 6
      result = BinaryPeek2(bb,10) ; Win top left Pos X
      Break
   Case 7
      result = BinaryPeek2(bb,12) ; Win top left  Pos Y
      Break
   Case 8
      result = BinaryPeek2(bb,14) ; Win bottom right Pos X
      Break
   Case 9
      result = BinaryPeek2(bb,16) ; Win bottom right  Pos Y
      Break
   Case 10
      result = BinaryPeek2(bb,18) ; Console Window Max Size X
      Break
   Case 11
      result = BinaryPeek2(bb,20) ; Console Window Max Size Y
      Break
   Case 0
      result = ""
      For i=0 To 10
         result = ItemInsert(BinaryPeek2(bb,i+i),-1,result,@TAB)
      Next
      Break
   Case request
      result = 0
      Break
   EndSelect
EndIf
BinaryFree(bb)
Return (result)
; dwSize
; COORD structure that contains the size, in character columns and rows, of the screen buffer.
; dwCursorPosition
; COORD structure that contains the column and row coordinates of the cursor in the screen buffer.
; wAttributes
; Attributes of the characters written to a screen buffer by the WriteFile and WriteConsole functions,
; or echoed to a screen buffer by the ReadFile and ReadConsole functions.
; For more information, see Character Attributes.
; srWindow
; SMALL_RECT structure that contains the screen buffer coordinates of the display window.
; Left   X-coordinate of the upper left corner of the rectangle.
; Top    Y-coordinate of the upper left corner of the rectangle.
; Right  X-coordinate of the lower right corner of the rectangle.
; Bottom Y-coordinate of the lower right corner of the rectangle.
; dwMaximumWindowSize
; COORD structure that contains the maximum size of the console window,
; given the current screen buffer size and font and the screen size.
;
; Retrieves information about the specified console screen buffer.
#EndFunction


#DefineFunction udfConSetScreenBufferSize (hOutput, colx, rowy)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"SetConsoleScreenBufferSize",long:hOutput,long:(colx+(rowy<<16)))
If (result==0) Then result=DllLastError()
Return (result)
; Changes the size of the specified console screen buffer.
#EndFunction


#DefineFunction udfConGetMaxWindowSize (handle, mode)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetLargestConsoleWindowSize",long:handle)
If (result==0)
   result=DllLastError()
Else
   Select mode
   Case 1
      result = result&65535 ; colx
      Break
   Case 2
      result = result>>16 ; rowy
      Break
   Case 0
      result = StrCat(result&65535," ",result>>16)
      Break
   Case mode
      result = 0
      Break
   EndSelect
EndIf
Return (result)
; mode=0 returns string e.g. "125 55"
; mode=1 returns columns x
; mode=2 returns rows y
; Retrieves the size of the largest possible console window.
#EndFunction


#DefineFunction udfConScrollScreenBuffer (hOutput, stlx, stly, sbrx, sbry, ctlx, ctly, cbrx, cbry, dcolx, drowy, char, attr)
bbscroll = BinaryAlloc(8)
BinaryPoke2(bbscroll,0,stlx)
BinaryPoke2(bbscroll,2,stly)
BinaryPoke2(bbscroll,4,sbrx)
BinaryPoke2(bbscroll,6,sbry)
bbclip = BinaryAlloc(8)
BinaryPoke2(bbclip,0,ctlx)
BinaryPoke2(bbclip,2,ctly)
BinaryPoke2(bbclip,4,cbrx)
BinaryPoke2(bbclip,6,cbry)
bbfill = BinaryAlloc(4)
BinaryPoke2(bbfill,0,Char2Num(char))
BinaryPoke2(bbfill,2,attr)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"ScrollConsoleScreenBufferA",long:hOutput,lpbinary:bbscroll,lpbinary:bbclip,long:(dcolx+(drowy<<16)),lpbinary:bbfill)
If (result==0) Then result=DllLastError()
BinaryFree(bbscroll)
BinaryFree(bbclip)
BinaryFree(bbfill)
Return (result)
; ScrollConsoleScreenBufferA(
;  hConsoleOutput     : Win32.Winnt.HANDLE;
;  lpScrollRectangle  : ac_SMALL_RECT_t;
;  lpClipRectangle    : ac_SMALL_RECT_t;
;  dwDestinationOrigin: COORD;
;  lpFill             : ac_CHAR_INFO_t)
; Moves a block of data in a screen buffer.
#EndFunction


#DefineFunction udfConSetWindowInfo (hOutput, tlx, tly, brx, bry, bAbs)
bAbs = Min(1,Max(0,bAbs))
bb = BinaryAlloc(8)
BinaryPoke2(bb,0,tlx)
BinaryPoke2(bb,2,tly)
BinaryPoke2(bb,4,brx)
BinaryPoke2(bb,6,bry)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"SetConsoleWindowInfo",long:hOutput,long:bAbs,lpbinary:bb)
If (result==0) Then result=DllLastError()
BinaryFree(bb)
Return (result)
; hConsoleOutput Handle to a console screen buffer. The handle must have GENERIC_WRITE access.
; bAbsolute Specifies how the coordinates in the structure pointed to by the lpConsoleWindow parameter are used.
; If bAbsolute is TRUE, the coordinates specify the new upper-left and lower-right corners of the window.
; If it is FALSE, the coordinates are offsets to the current window-corner coordinates.
; lpConsoleWindow Pointer to a SMALL_RECT structure that contains values that determine
; the new upper-left and lower-right corners of the window.
;
; Sets the current size and position of a console screen buffer's window.
#EndFunction


#DefineFunction udfConFillScreenBuffer (hOutput, char, attr)
bb = BinaryAlloc(22)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetConsoleScreenBufferInfo",long:hOutput,lpbinary:bb)
If (result==0)
   result=DllLastError()
Else
   BinaryEodSet(bb,22)
   len = BinaryPeek2(bb,0) * BinaryPeek2(bb,2)
   bbcount = BinaryAlloc(4)
   result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"FillConsoleOutputAttribute",long:hOutput,long:attr,long:len,long:0,lpbinary:bbcount)
   If (result==0)
      result=DllLastError()
   Else
      result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"FillConsoleOutputCharacterA",long:hOutput,long:Char2Num(char),long:len,long:0,lpbinary:bbcount)
      If (result==0)
         result=DllLastError()
      EndIf
   EndIf
EndIf
BinaryFree(bbcount)
BinaryFree(bb)
Return (result)
; Fills the entire screenbuffer with character and attribute, does a "cls" or "clearscreen".
#EndFunction
;
; ----- SCREENBUFFER METRICS ----------------------------------------------------------------------------------------------------



; ----- CURSOR ------------------------------------------------------------------------------------------------------------------
;
#DefineFunction udfConGetCursorInfo (hOutput)
bb = BinaryAlloc(5)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetConsoleCursorInfo",long:hOutput,lpbinary:bb)
If (result==0)
   result=DllLastError()
Else
   BinaryEodSet(bb,5)
   result=StrCat(BinaryPeek4(bb,0)," ",BinaryPeek(bb,4))
EndIf
BinaryFree(bb)
Return (result)
; dwSize Percentage of the character cell that is filled by the cursor, value is between 1 and 100.
; The cursor appearance varies, ranging from completely filling the cell down to a horizontal line at the bottom of the cell.
; bVisible Visibility of the cursor. If the cursor is visible, this member is TRUE.
; This udf returns a string of two integer numbers, e.g. "12 1"
; dwSize 1..100
; bVisible 0..1
;
; Retrieves information about the size and visibility of the cursor for the specified console screen buffer.
#EndFunction


#DefineFunction udfConSetCursorInfo (hOutput, infostr)
If (ParseData(infostr)<>2) Then Return (0)
bb = BinaryAlloc(5)
BinaryPoke4(bb,0,Min(100,Max(1,param1))) ; percentage 1..100 (should be 1..99, because 100 is weird empty cell)
BinaryPoke(bb,4,Min(1,Max(0,param2)))  ; 0..1 resp @false..@true
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"SetConsoleCursorInfo",long:hOutput,lpbinary:bb)
If (result==0) Then result=DllLastError()
BinaryFree(bb)
Return (result)
; dwSize Percentage of the character cell that is filled by the cursor, value range is 1..100.
; The cursor appearance varies, ranging from completely filling the cell down to a horizontal line at the bottom of the cell.
; bVisible Visibility of the cursor. If the cursor is visible, this member is TRUE.
; infostr is a string e.g. "50,1" or "50|1", composed of "integer,delimiter,integer".
; If bVisible was set to false, then the dwSize is somewhat undefined (don't know for sure what happens there)
; therefore it needs always setting of both values at one time.
;
; Sets the size and visibility of the cursor for the specified console screen buffer.
#EndFunction


#DefineFunction udfConSetCursorPos (hOutput, colx, rowy)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"SetConsoleCursorPosition",long:hOutput,long:(colx+(rowy<<16)))
If (result==0) Then result=DllLastError()
Return (result)
; colx = 0..maxx
; rowy = 0..maxy
; Sets the cursor position in the specified console screen buffer.
#EndFunction
;
; ----- CURSOR ------------------------------------------------------------------------------------------------------------------




; ----- WRITEFILE READFILE ------------------------------------------------------------------------------------------------------
;
#DefineFunction udfWriteFile (hOutput, str)
bbsize = StrLen(str)
bb = BinaryAlloc(bbsize)
BinaryPokeStr(bb,0,str)
bbcount = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"WriteFile",long:hOutput,lpbinary:bb,long:bbsize,lpbinary:bbcount,lpnull)
If (result==0) Then result=DllLastError()
BinaryFree(bbcount)
BinaryFree(bb)
Return (result)
; note: we do not use content of bbcount for anything in this implementation
#EndFunction


#DefineFunction udfReadFile (hInput)
bbsize = 4096 ; buffer is sized for file read, not for keyboard input
bb = BinaryAlloc(bbsize)
bbcount = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"ReadFile",long:hInput,lpbinary:bb,long:bbsize,lpbinary:bbcount,lpnull)
If (result==0)
   result=DllLastError()
Else
   BinaryEodSet(bb,bbsize)
   result = BinaryPeekStr(bb,0,bbsize)
EndIf
BinaryFree(bb)
BinaryFree(bbcount)
Return (result)
; note: we do not use content of bbcount for anything in this implementation
#EndFunction
;
;
; ----- WRITEFILE READFILE ------------------------------------------------------------------------------------------------------



; ----- CONSOLE WRITE READ ------------------------------------------------------------------------------------------------------
;
#DefineFunction udfConWriteConsole (hOutput, str)
bbsize = StrLen(str)
bb = BinaryAlloc(bbsize)
BinaryPokeStr(bb,0,str)
bbcount = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"WriteConsoleA",long:hOutput,lpbinary:bb,long:bbsize,lpbinary:bbcount,lpnull)
If (result==0) Then result=DllLastError()
BinaryFree(bbcount)
BinaryFree(bb)
Return (result)
; Writes a character string to a console screen buffer beginning at the current cursor location.
#EndFunction


#DefineFunction udfConReadConsole (hInput)
bbsize = 255 ; keyboard input buffer
bb = BinaryAlloc(bbsize)
bbcount = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"ReadConsoleA",long:hInput,lpbinary:bb,long:bbsize,lpbinary:bbcount,lpnull)
If (result==0)
   result=DllLastError()
Else
   BinaryEodSet(bb,bbsize)
   result=BinaryPeekStr(bb,0,bbsize)
EndIf
BinaryFree(bbcount)
BinaryFree(bb)
Return (result)
; Reads character input from the console input buffer and removes it from the buffer.
#EndFunction
;
; ----- CONSOLE WRITE READ FLUSH ------------------------------------------------------------------------------------------------



; ----- WRITE READ LOW LEVEL ----------------------------------------------------------------------------------------------------
;
#DefineFunction udfConFlushInputBuffer (hInput)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"FlushConsoleInputBuffer",long:hInput)
If (result==0) Then result=DllLastError()
Return (result)
; Flushes the console input buffer.
#EndFunction


#DefineFunction udfConSetTextAttribute (hOutput, attr)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"SetConsoleTextAttribute",long:hOutput,long:attr)
If (result==0) Then result=DllLastError()
Return (result)
; Sets the foreground (text) and background color attributes of characters written to the screen buffer.
#EndFunction


#DefineFunction udfBinaryAllocCharAttrBuf (tlx, tly, brx, bry)
bbsize = ((brx-tlx+1)*(bry-tly+1))<<2
bb = BinaryAlloc(bbsize)
BinaryEodSet(bb,bbsize)
Return (bb)
; Returns a handle to a binary buffer, utilized for combined storage of character and attribut, 4 byte per cell.
#EndFunction


#DefineFunction udfBinaryAllocAttrBuf (len)
bbsize = len<<1
bb = BinaryAlloc(bbsize)
BinaryEodSet(bb,bbsize)
Return (bb)
; Returns a handle to a binary buffer, utilized for attribute storage, 2 byte per cell.
#EndFunction


#DefineFunction udfConReadOutputRegion (hOutput, tlx, tly, brx, bry, bbCharAttr)
bbregion = BinaryAlloc(8)
BinaryPoke2(bbregion,0,tlx)
BinaryPoke2(bbregion,2,tly)
BinaryPoke2(bbregion,4,brx)
BinaryPoke2(bbregion,6,bry)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"ReadConsoleOutputA",long:hOutput,lpbinary:bbCharAttr,long:(brx-tlx+1)+((bry-tly+1)<<16),long:0,lpbinary:bbregion)
If (result==0) Then result=DllLastError()
BinaryFree(bbregion)
Return (result)
; ReadConsoleOutputA(
; hConsoleOutput: HANDLE;
; lpBuffer      : PCHAR_INFO;
; dwBufferSize  : COORD;
; dwBufferCoord : COORD; = 0; tlx, top left destination cell of the temporary buffer is colx=0, rowy=0
; lpReadRegion  : PSMALL_RECT)
; Reads character and color attribute data from a rectangular block of character cells in a console screen buffer.
#EndFunction


#DefineFunction udfConWriteOutputRegion (hOutput, tlx, tly, brx, bry, bbCharAttr)
bbregion = BinaryAlloc(8)
BinaryPoke2(bbregion,0,tlx)
BinaryPoke2(bbregion,2,tly)
BinaryPoke2(bbregion,4,brx)
BinaryPoke2(bbregion,6,bry)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"WriteConsoleOutputA",long:hOutput,lpbinary:bbCharAttr,long:(brx-tlx+1)+((bry-tly+1)<<16),long:0,lpbinary:bbregion)
If (result==0) Then result=DllLastError()
BinaryFree(bbregion)
Return (result)
; WriteConsoleOutputA(
; hConsoleOutput: HANDLE;
; lpBuffer      : PCHAR_INFO;
; dwBufferSize  : COORD;
; dwBufferCoord : COORD; = 0; tlx, top left destination cell of the temporary buffer is colx=0, rowy=0
; lpWriteRegion : PSMALL_RECT)
; Writes character and color attribute data to a specified rectangular block of character cells in a console screen buffer.
#EndFunction


#DefineFunction udfConReadOutputChar (hOutput, colx, rowy, len)
bb = BinaryAlloc(len)
BinaryEodSet(bb,len)
bbcount = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"ReadConsoleOutputCharacterA",long:hOutput,lpbinary:bb,long:len,long:(colx+(rowy<<16)),lpbinary:bbcount)
If (result==0)
   result=DllLastError()
Else
   result=BinaryPeekStr(bb,0,len)
EndIf
BinaryFree(bb)
BinaryFree(bbcount)
Return (result)
; BOOL ReadConsoleOutputCharacter(
;  HANDLE hConsoleOutput,       // handle to screen buffer
;  LPTSTR lpCharacter,          // character buffer
;  DWORD nLength,               // number of cells to read
;  COORD dwReadCoord,           // coordinates of first cell
;  LPDWORD lpNumberOfCharsRead  // number of cells read
; Copies a number of characters from consecutive cells of a console screen buffer.
#EndFunction


#DefineFunction udfConReadOutputAttr (hOutput, colx, rowy, len, bbAttr)
bbcount = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"ReadConsoleOutputAttribute",long:hOutput,lpbinary:bbAttr,long:len,long:(colx+(rowy<<16)),lpbinary:bbcount)
If (result==0) Then result=DllLastError()
BinaryFree(bbcount)
Return (result)
; BOOL ReadConsoleOutputCharacter(
;  HANDLE hConsoleOutput,       // handle to screen buffer
;  LPTSTR lpAttribute,          // attribute buffer
;  DWORD nLength,               // number of cells to read
;  COORD dwReadCoord,           // coordinates of first cell
;  LPDWORD lpNumberOfAttrsRead  // number of cells read
; Copies a specified number of foreground and background color attributes from consecutive cells of a console screen buffer
; into a prepared binary buffer "bbAttr".
#EndFunction


#DefineFunction udfConFillOutputChar (hOutput, colx, rowy, len, char)
bbcount = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"FillConsoleOutputCharacterA",long:hOutput,long:Char2Num(char),long:len,long:(colx+(rowy<<16)),lpbinary:bbcount)
If (result==0) Then result=DllLastError()
BinaryFree(bbcount)
Return (result)
; Writes a character to the screen buffer a specified number of times.
#EndFunction


#DefineFunction udfConFillOutputAttr (hOutput, colx, rowy, len, attr)
bbcount = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"FillConsoleOutputAttribute",long:hOutput,long:attr,long:len,long:(colx+(rowy<<16)),lpbinary:bbcount)
If (result==0) Then result=DllLastError()
BinaryFree(bbcount)
Return (result)
; FillConsoleOutputAttribute(
;  hStdout,          // screen buffer handle
;  wColor,           // color to fill with
;  80*50,            // number of cells to fill
;  coord,            // first cell to write to
;  &cWritten);       // actual number written
; Sets the text and background color attributes for a specified number of character cells.
#EndFunction


#DefineFunction udfConWriteCharStr (hOutput, colx, rowy, str)
bbcount = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"WriteConsoleOutputCharacterA",long:hOutput,lpstr:str,long:StrLen(str),long:(colx+(rowy<<16)),lpbinary:bbcount)
If (result==0) Then result=DllLastError()
BinaryFree(bbcount)
Return (result)
; Copies a number of characters to consecutive cells of a console screen buffer.
#EndFunction


#DefineFunction udfConWriteAttr (hOutput, colx, rowy, bbattr)
len = BinaryEodGet(bbattr)/2 ; 2 byte per Attribute, see udfBinaryAllocAttrBuf (len)
bbcount = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"WriteConsoleOutputAttribute",long:hOutput,lpbinary:bbattr,long:len,long:(colx+(rowy<<16)),lpbinary:bbcount)
If (result==0) Then result=DllLastError()
BinaryFree(bbcount)
Return (result)
; Copies a number of foreground and background color attributes to consecutive cells of a console screen buffer
; from a prepared binary buffer "bbAttr".
#EndFunction
;
; ----- WRITE READ LOW LEVEL ----------------------------------------------------------------------------------------------------



; ----- CODEPAGE ----------------------------------------------------------------------------------------------------------------
;
#DefineFunction udfConGetInputCP ()
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetConsoleCP")
If (result==0) Then result=DllLastError()
Return (result)
; Retrieves the input code page used by the console associated with the calling process.
#EndFunction


#DefineFunction udfConGetOutputCP ()
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetConsoleOutputCP")
If (result==0) Then result=DllLastError()
Return (result)
; Retrieves the output code page used by the console associated with the calling process.
#EndFunction


#DefineFunction udfConSetInputCP (CodePageID)
;result = DLLCall(StrCat(DirWindows(1),"kernel32.dll"),long:"SetConsoleCP",long:wCodePageID)
;if (result==0) then result=DllLastError()
;Return (result)
; Windows 95/98/Me: Unsupported.
; wCodePageID
; Specifies the identifier of the code page to set.
; The identifiers of the code pages available on the local computer are stored in the registry under the following key.
; HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage
; Windows NT/2000/XP: This function uses either Unicode characters or 8-bit characters from the console's current code page.
; The console's code page defaults initially to the system's OEM code page.
; To change the console's code page, use the SetConsoleCP or SetConsoleOutputCP functions,
; or use the chcp or mode con cp select= commands.
;
; Sets the input code page used by the console associated with the calling process.
#EndFunction


#DefineFunction udfConSetOutputCP (CodePageID)
;result = DLLCall(StrCat(DirWindows(1),"kernel32.dll"),long:"SetConsoleOutputCP",long:wCodePageID)
;if (result==0) then result = DllLastError()
;Return (result)
; Windows 95/98/Me: Unsupported.
;
; Sets the output code page used by the console associated with the calling process.
#EndFunction
;
; ----- CODEPAGE ----------------------------------------------------------------------------------------------------------------



; ----- MOUSE ------------------------------------------------------------------------------------------------------------------
;
#DefineFunction udfConGetNumberMouseButtons ()
bb = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetNumberOfConsoleMouseButtons",lpbinary:bb)
If (result==0)
   result=DllLastError()
Else
   BinaryEodSet(bb,4)
   result=BinaryPeek4(bb,0)
EndIf
BinaryFree(bb)
Return (result)
; Retrieves the number of buttons on the mouse used by the current console.
#EndFunction
;
; ----- MOUSE -------------------------------------------------------------------------------------------------------------------



; ----- EVENTS ------------------------------------------------------------------------------------------------------------------
;
#DefineFunction udfConGetNumberInputEvents (hInput)
bb = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetNumberOfConsoleInputEvents",long:hInput,lpbinary:bb)
If (result==0)
   result=DllLastError()
Else
   BinaryEodSet(bb,4)
   result=BinaryPeek4(bb,0)
EndIf
BinaryFree(bb)
Return (result)
; Retrieves the number of unread input records in the console's input buffer.
#EndFunction


#DefineFunction udfConWriteConsoleInput (hInput, bbEvent)
bbsize = BinaryEodGet(bbEvent)
bbcount = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"WriteConsoleInputA",long:hInput,lpbinary:bbEvent,long:bbsize,lpbinary:bbcount)
If (result==0) Then result=DllLastError()
BinaryFree(bbcount)
Return (result)
; WriteConsoleInputA(
;  hConsoleInput          : Win32.Winnt.HANDLE;
;  lpBuffer               : ac_INPUT_RECORD_t;
;  nLength                : Win32.DWORD;
;  lpNumberOfEventsWritten: Win32.LPDWORD)
; Writes data directly to the console input buffer.
#EndFunction


#DefineFunction udfConReadConsoleInput (hInput, bbEvent)
bbsize = BinaryEodGet(bbEvent)
bbcount = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"ReadConsoleInputA",long:hInput,lpbinary:bbEvent,long:bbsize,lpbinary:bbcount)
If (result==0)
   result=DllLastError()
Else
   BinaryEodSet(bbcount,4)
   result=BinaryPeek4(bbcount,0)
EndIf
BinaryFree(bbcount)
Return (result)
; ReadConsoleInputA(
;  hConsoleInput       : Win32.Winnt.HANDLE;
;  lpBuffer            : PINPUT_RECORD;
;  nLength             : Win32.DWORD;
;  lpNumberOfEventsRead: Win32.LPDWORD)
; Reads data from a console input buffer and removes it from the buffer.
#EndFunction


#DefineFunction udfConPeekConsoleInput (hInput, bbEvent)
bbsize = BinaryEodGet(bbEvent)
bbcount = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"PeekConsoleInputA",long:hInput,lpbinary:bbEvent,long:bbsize,lpbinary:bbcount)
If (result==0)
   result=DllLastError()
Else
   BinaryEodSet(bbcount,4)
   result=BinaryPeek4(bbcount,0)
EndIf
BinaryFree(bbcount)
Return (result)
; PeekConsoleInputA(
;  hConsoleInput       : Win32.Winnt.HANDLE;
;  lpBuffer            : PINPUT_RECORD;
;  nLength             : Win32.DWORD;
;  lpNumberOfEventsRead: Win32.LPDWORD)
; Reads data from the specified console input buffer without removing it from the buffer.
#EndFunction
;
; ----- EVENTS ------------------------------------------------------------------------------------------------------------------



; ----- NOT WIN 98 --------------------------------------------------------------------------------------------------------------
;
#DefineFunction udfConGetConsoleWindow ()
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetConsoleWindow")
If (result==0) Then result=DllLastError()
Return (result)
; Windows NT/2000/XP: Included in Windows 2000 and later.
; Windows 95/98/Me: Unsupported
; Retrieves the window handle used by the console associated with the calling process.
#EndFunction


#DefineFunction udfConGetDisplayMode ()
bb = BinaryAlloc(4)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetConsoleDisplayMode",lpbinary:bb)
If (result==0)
   result=DllLastError()
Else
   BinaryEodSet(bb,4)
   result=BinaryPeek4(bb,0)
EndIf
BinaryFree(bb)
Return (result)
; CONSOLE_FULLSCREEN = 1
; CONSOLE_FULLSCREEN_HARDWARE = 2
; Windows 95/98/Me: Unsupported
; Retrieves the display mode of the current console.
#EndFunction


;#DefineFunction udfConSetCtrlHandler (HandlerRoutine, Add)
;bb = BinaryAlloc(4)
;result = DLLCall(StrCat(DirWindows(1),"kernel32.dll"),long:"SetConsoleCtrlHandler",lpbinary:HandlerRoutine, long:Add)
;If (result==0)
;   result=DllLastError()
;else
;   BinaryEodSet(bb,4)
;   result=BinaryPeek4(bb,0)
;EndIf
;BinaryFree(bb)
;Return (result)
;; Adds or removes an application-defined HandlerRoutine from the list of handler functions for the calling process.
;#EndFunction
;
;
; ----- NOT WIN 98 --------------------------------------------------------------------------------------------------------------



; -------------------------------------------------------------------------------------------------------------------------------
; MSDN Home >  MSDN Library >  DLLs, Processes, and Threads >  Character-Mode Applications >  Console Reference
; Platform SDK: DLLs, Processes, and Threads
; Platform SDK Release: November 2001
; -------------------------------------------------------------------------------------------------------------------------------
; Console Functions
; The following functions are used to access a console.
; -------------------------------------------------------------------------------------------------------------------------------;
; Function Description
; # 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 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.
; # 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.
; # GetConsoleMode Retrieves the current input mode of a console's input buffer or the current output mode of a console screen buffer.
; # 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.
; - GetConsoleSelectionInfo Retrieves information about the current console selection.
; # GetConsoleTitle Retrieves the title bar string 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.
; # 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.
; # 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.
;   HandlerRoutine An application-defined function used with the SetConsoleCtrlHandler function.
; # 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.
; # 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.
; # SetConsoleScreenBufferSize Changes the size of the specified console screen buffer.
; # SetConsoleTextAttribute Sets the foreground (text) and background color attributes of characters written to the screen buffer.
; # SetConsoleTitle Sets the title bar string for the current console window.
; # SetConsoleWindowInfo Sets the current size and position of a console screen buffer's window.
;   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.
; -------------------------------------------------------------------------------------------------------------------------------
; # implemented, supported in Win98
; - not implemented, unsupported in Win98
; -------------------------------------------------------------------------------------------------------------------------------
;
; Remarks
;
; A console consists of an input buffer and one or more screen buffers.
; The mode of a console buffer determines how the console behaves during input or output (I/O) operations.
; One set of flag constants is used with input handles, and another set is used with screen buffer (output) handles.
; Setting the output modes of one screen buffer does not affect the output modes of other screen buffers.
;
; The ENABLE_LINE_INPUT and ENABLE_ECHO_INPUT modes only affect processes
; that use ReadFile or ReadConsole to read from the console's input buffer.
; Similarly, the ENABLE_PROCESSED_INPUT mode primarily affects ReadFile and ReadConsole users,
; except that it also determines whether CTRL+C input is reported in the input buffer
; (to be read by the ReadConsoleInput function) or is passed to a function defined by the application.
;
; The ENABLE_WINDOW_INPUT and ENABLE_MOUSE_INPUT modes determine whether user interactions
; involving window resizing and mouse actions are reported in the input buffer or discarded.
; These events can be read by ReadConsoleInput, but they are always filtered by ReadFile and ReadConsole.
;
; The ENABLE_PROCESSED_OUTPUT and ENABLE_WRAP_AT_EOL_OUTPUT modes only affect processes
; using ReadFile or ReadConsole and WriteFile or WriteConsole.
;
; To change a console's I/O modes, call SetConsoleMode function.
; -------------------------------------------------------------------------------------------------------------------------------
;
; GetConsoleMode
;
; If the hConsoleHandle parameter is an input handle, the mode can be a combination of the following values.
; When a console is created, all input modes except ENABLE_WINDOW_INPUT are enabled by default.
;
; ENABLE_LINE_INPUT
; The ReadFile or ReadConsole function returns only when a carriage return character is read.
; If this mode is disabled, the functions return when one or more characters are available.
;
; ENABLE_ECHO_INPUT
; Characters read by the ReadFile or ReadConsole function are written to the active screen buffer as they are read.
; This mode can be used only if the ENABLE_LINE_INPUT mode is also enabled.
;
; ENABLE_PROCESSED_INPUT
; CTRL+C is processed by the system and is not placed in the input buffer.
; If the input buffer is being read by ReadFile or ReadConsole,
; other control keys are processed by the system and are not returned in the ReadFile or ReadConsole buffer.
; If the ENABLE_LINE_INPUT mode is also enabled, backspace, carriage return, and linefeed characters are handled by the system.
;
; ENABLE_WINDOW_INPUT
; User interactions that change the size of the console screen buffer are reported in the console's input buffer.
; Information about these events can be read from the input buffer by applications using the ReadConsoleInput function,
; but not by those using ReadFile or ReadConsole.
;
; ENABLE_MOUSE_INPUT
; If the mouse pointer is within the borders of the console window and the window has the keyboard focus,
; mouse events generated by mouse movement and button presses are placed in the input buffer.
; These events are discarded by ReadFile or ReadConsole, even when this mode is enabled.
;
;
; If the hConsoleHandle parameter is a screen buffer handle, the mode can be a combination of the following values.
; When a screen buffer is created, both output modes are enabled by default.
;
; ENABLE_PROCESSED_OUTPUT
; Characters written by the WriteFile or WriteConsole function or echoed by the ReadFile or ReadConsole function
; are parsed for ASCII control sequences, and the correct action is performed.
; Backspace, tab, bell, carriage return, and linefeed characters are processed.
;
; ENABLE_WRAP_AT_EOL_OUTPUT
; When writing with WriteFile or WriteConsole or echoing with ReadFile or ReadConsole,
; the cursor moves to the beginning of the next row when it reaches the end of the current row.
; This causes the rows displayed in the console window to scroll up automatically
; when the cursor advances beyond the last row in the window.
; It also causes the contents of the screen buffer to scroll up (discarding the top row of the screen buffer)
; when the cursor advances beyond the last row in the screen buffer.
; If this mode is disabled, the last character in the row is overwritten with any subsequent characters.
; -------------------------------------------------------------------------------------------------------------------------------
;
; SetConsoleWindowInfo
;
; The function fails if the specified window rectangle extends beyond the boundaries of the screen buffer.
; This means that the Top and Left members of the lpConsoleWindow rectangle
; (or the calculated top and left coordinates, if bAbsolute is FALSE) cannot be less than zero.
; Similarly, the Bottom and Right members (or the calculated bottom and right coordinates)
; cannot be greater than (screen buffer height – 1) and (screen buffer width – 1), respectively.
; The function also fails if the Right member (or calculated right coordinate)
; is less than or equal to the Left member (or calculated left coordinate)
; or if the Bottom member (or calculated bottom coordinate) is less than or equal
; to the Top member (or calculated top coordinate).
;
; For consoles with more than one screen buffer, changing the window location for one screen buffer
; does not affect the window locations of the other screen buffers.
;
; To determine the current size and position of a screen buffer's window, use the GetConsoleScreenBufferInfo function.
; This function also returns the maximum size of the window,
; given the current screen buffer size, the current font size, and the screen size.
; The GetLargestConsoleWindowSize function returns the maximum window size given the current font and screen sizes,
; but it does not consider the size of the screen buffer.
;
; SetConsoleWindowInfo can be used to scroll the contents of the screen buffer
; by shifting the position of the window rectangle without changing its size.
; -------------------------------------------------------------------------------------------------------------------------------
;
; SetStdHandle
;
; The standard handles of a process may have been redirected by a call to SetStdHandle,
; in which case GetStdHandle will return the redirected handle.
; If the standard handles have been redirected, you can specify the CONIN$ value in a call
; to the CreateFile function to get a handle to a console's input buffer.
; Similarly, you can specify the CONOUT$ value to get a handle to the console's active screen buffer.
; -------------------------------------------------------------------------------------------------------------------------------
;
; GetStdHandle
;
; Handles returned by GetStdHandle can be used by applications that need to read from or write to the console.
; When a console is created, the standard input handle is a handle to the console's input buffer,
; and the standard output and standard error handles are handles of the console's active screen buffer.
; These handles can be used by the ReadFile and WriteFile functions,
; or by any of the console functions that access the console input buffer or a screen buffer
; (for example, the ReadConsoleInput, WriteConsole, or GetConsoleScreenBufferInfo functions).
;
; All handles returned by this function have GENERIC_READ and GENERIC_WRITE access
; unless the function has been used to set a standard handle to be some handle with a lesser access.
;
; The standard handles of a process may be redirected by a call to SetStdHandle,
; in which case GetStdHandle returns the redirected handle.
; If the standard handles have been redirected, you can specify the CONIN$ value
; in a call to the CreateFile function to get a handle to a console's input buffer.
; Similarly, you can specify the CONOUT$ value to get a handle to a console's active screen buffer.
; -------------------------------------------------------------------------------------------------------------------------------
;
; WriteConsole
;
; WriteConsole writes characters to a console screen buffer.
; It behaves like the WriteFile function, except it can write in either Unicode or ANSI mode.
; To create an application that maintains a single set of sources compatible with both modes,
; use WriteConsole rather than WriteFile.
; Although WriteConsole can be used only with a console screen buffer handle,
; WriteFile can be used with other handles (such as files or pipes).
; WriteConsole fails if used with a standard handle that has been redirected to be something other than a console handle.
;
; Although an application can use WriteConsole in ANSI mode to write ANSI characters,
; consoles do not support ANSI escape sequences.
; However, some functions provide equivalent functionality:
; for example, SetCursorPos, SetConsoleTextAttribute, and GetConsoleCursorInfo.
;
; WriteConsole writes characters to the screen buffer at the current cursor position.
; The cursor position advances as characters are written.
; The SetConsoleCursorPosition function sets the current cursor position.
;
; Characters are written using the foreground and background color attributes associated with the screen buffer.
; The SetConsoleTextAttribute function changes these colors.
; To determine the current color attributes and the current cursor position, use GetConsoleScreenBufferInfo.
;
; All of the input modes that affect the behavior of WriteFile have the same effect on WriteConsole.
; To retrieve and set the output modes of a console screen buffer, use the GetConsoleMode and SetConsoleMode functions.
;
; Windows NT/2000/XP:
; This function uses either Unicode characters or ANSI characters from the console's current code page.
; The console's code page defaults initially to the system's OEM code page.
; To change the console's code page, use the SetConsoleCP or SetConsoleOutputCP functions,
; or use the chcp or mode con cp select= commands.
;
; Windows 95/98/Me:
; WriteConsoleW is supported by the Microsoft Layer for Unicode.
; To use this, you must add certain files to your application,
; as outlined in Microsoft Layer for Unicode on Windows 95/98/Me Systems.
; -------------------------------------------------------------------------------------------------------------------------------
;
; SetStdHandle
;
; The standard handles of a process may have been redirected by a call to SetStdHandle,
; in which case GetStdHandle will return the redirected handle.
; If the standard handles have been redirected,
; you can specify the CONIN$ value in a call to the CreateFile function
; to get a handle to a console's input buffer.
; Similarly, you can specify the CONOUT$ value to get a handle to the console's active screen buffer.
; -------------------------------------------------------------------------------------------------------------------------------
;
; Gotta say "Thanks" to:
; JRC jrc@progeni.com
; kdmoyers admin@guden.com -Kirby
; ... and to the ultimative documentation by Microsoft
; ... and the google machine too.
; Detlev Dalitz.20020215
; -------------------------------------------------------------------------------------------------------------------------------
; Platform SDK Release: November 2001
; © 2002 Microsoft Corporation. All rights reserved.
; -------------------------------------------------------------------------------------------------------------------------------


#DefineFunction udfConRandomFillWindow (hOutput)
bb = BinaryAlloc(22)
result = DllCall(StrCat(DirWindows(1),"kernel32.dll"),long:"GetConsoleScreenBufferInfo",long:hOutput,lpbinary:bb)
If (result==0)
   result=DllLastError()
Else
   BinaryEodSet(bb,22)
   tlx = BinaryPeek2(bb,10) ; Win top left Pos X
   tly = BinaryPeek2(bb,12) ; Win top left  Pos Y
   brx = BinaryPeek2(bb,14) ; Win bottom right Pos X
   bry = BinaryPeek2(bb,16) ; Win bottom right  Pos Y
   xmax = 1+brx-tlx
   ymax = 1+bry-tly
   bbrsize = xmax * ymax
   bbrmax = bbrsize-1

   bbcount = BinaryAlloc(4)
   kernel32dll = StrCat(DirWindows(1),"kernel32.dll")
   AttrBack = Random(15)
   CharGroup = Random(8)

   clist = ""
   For i=0 To bbrmax
      clist = ItemInsert(((i mod xmax)+((i/xmax)<<16)),-1,clist,@TAB)
   Next

   While 1
      Select CharGroup
      Case 0
         charstr = " "
         Break
      Case 1
         charstr = "+"
         Break
      Case 2
         charstr = "*"
         Break
      Case 3
         charstr = "!"
         Break
      Case 4
         charstr = "#"
         Break
      Case 5
         charstr = Num2Char(48+Random(9))
         Break
      Case 6
         charstr = Num2Char(199+Random(8))
         Break
      Case 7
         charstr = Num2Char(191+Random(7))
         Break
      Case 8
         charstr = Num2Char(33+Random(14))
         Break
      EndSelect

      ir = 1+Random(bbrmax)
      cell = ItemExtract(ir,clist,@TAB)
      clist = ItemRemove(ir,clist,@TAB)
      bbrmax = bbrmax-1

      If (charstr==" ")
         attrstr = StrCat(Num2Char(AttrBack<<4),Num2Char(0))
      Else
         AttrFore = Random(15)
         AttrFore = AttrFore+(AttrFore==AttrBack)
         attrstr = StrCat(Num2Char(AttrFore|(AttrBack<<4)),Num2Char(0))
      EndIf

      result = DllCall(kernel32dll,long:"WriteConsoleOutputAttribute",long:hOutput,lpstr:attrstr,long:1,long:cell,lpbinary:bbcount)
      If (result==0)
         result=DllLastError()
         Break
      EndIf

      result = DllCall(kernel32dll,long:"WriteConsoleOutputCharacterA",long:hOutput,lpstr:charstr,long:1,long:cell,lpbinary:bbcount)
      If (result==0)
         result=DllLastError()
         Break
      EndIf

      If (bbrmax<0) Then Break

      ; If IsKeyDown(@shift) then break ; in console mode this gives not @true with shift key pressed !?!?!?
      ; If IsKeyDown(@ctrl) then break  ; in console mode this gives @true without any key pressed !?!?!?
      ; todo ==> we have to make a separate console "getkey" function, may be peek it directly from the input buffer

   EndWhile
EndIf
BinaryFree(bb)
BinaryFree(bbcount)
TimeDelay(1)
Return (result)
; Fills the entire screenbuffer with random character and random attribute, does a colored "cls" or "clearscreen".
#EndFunction


#DefineFunction udfConSaveRegionToFile (hOutput, tlx, tly,