Search code examples
winapiconsoleforth

How to use ReadConsoleOutputCharacterA in Forth?


I use

WINAPI: ReadConsoleOutputCharacterA KERNEL32.DLL

which seems to work, but how to handle the in and out parameters? Especially, how to get

hConsoleOutput [in] A handle to the console screen buffer. The handle must have the GENERIC_READ access right. For more information, see Console Buffer Security and Access Rights.


Solution

  • hConsoleOutput there is just an appropriate handle as is. Some usage example for ReadConsoleOutputCharacter can be found in devel directory (contribution).

    Example of this API usage:

    \ Global variables in dictionary space just for learning,
    \ -- don't use such approach, especially in multithreading.
    VARIABLE lpNumberOfCharsRead
    CREATE lpCharacter 5 CHARS ALLOT \ buffer for 5 chars
    
    : XYC@ ( x y -- c )
      16 LSHIFT OR >R \ COORD
      0 lpCharacter C!
      lpNumberOfCharsRead \ _Out_ LPDWORD lpNumberOfCharsRead
      R> \ dwReadCoord
      1  \ nLength  \ to read
      lpCharacter \ _Out_ LPTSTR  lpCharacter
      H-STDOUT
      ReadConsoleOutputCharacterA ERR THROW
      lpCharacter C@
    ;
    
    \ test
    0 0 XYC@ EMIT
    

    Useful wrapper:

    : READOUT-CONSOLE-XY ( a-buf u x y -- a-buf u2 ior )
      2SWAP 2>R 16 LSHIFT OR >R
      0 SP@ R>          ( 0 addr-cnt coord )
      R> R@ H-STDOUT    ( 0 addr-cnt coord u a-buf handle )
      ReadConsoleOutputCharacterA ERR ( u2 ior )
      R> -ROT
    ;
    
    \ test
    HERE 50 0 0 READOUT-CONSOLE-XY THROW  TYPE