Search
Module:
Directory

   Desktop Functions:

   Smart Device Functions:


Show Recent Changes
Subscribe (RSS)
Misc. Pages
Comments
FAQ
Helpful Tools
Playground
Suggested Reading
Website TODO List
Download Visual Studio Add-In

ReadConsoleOutput (kernel32)
 
.
Summary
Summary

C# Signature:

[DllImport("kernel32.dll")]
static extern bool ReadConsoleOutputCharacter(IntPtr hConsoleOutput,
   [Out] StringBuilder lpCharacter, uint nLength, COORD dwReadCoord,
   out uint lpNumberOfCharsRead);
static extern bool ReadConsoleOutput(IntPtr hConsoleOutput, [Out] CHAR_INFO []
   lpBuffer, COORD dwBufferSize, COORD dwBufferCoord,
   ref SMALL_RECT lpReadRegion);

User-Defined Types:

None.

    //these may be defined elsewhere on this site, but it seems handy to have them
    // all in one place

Notes:

None.

    //CHAR_INFO struct, which was a union in the old days
    // so we want to use LayoutKind.Explicit to mimic it as closely
    // as we can
    [StructLayout(LayoutKind.Explicit)]
    private struct CHAR_INFO
    {
        [FieldOffset(0)]
        internal char UnicodeChar;
        [FieldOffset(0)]
        internal char AsciiChar;
        [FieldOffset(2)] //2 bytes seems to work properly
        internal UInt16 Attributes;
    }

Tips & Tricks:

Please add some!

    //COORD struct
    [StructLayout(LayoutKind.Sequential)]
    private struct COORD
    {
        public short X;
        public short Y;
    }

Sample Code:

[DllImport("Kernel32", SetLastError=true)]
static extern IntPtr GetStdHandle(uint nStdHandle);
    //SMALL_RECT struct
    [StructLayout(LayoutKind.Sequential)]
    private struct SMALL_RECT
    {
        public short Left;
        public short Top;
        public short Right;
        public short Bottom;
    }

[DllImport("Kernel32", SetLastError=true)]
static extern bool ReadConsoleOutputCharacter(IntPtr hConsoleOutput,
    [Out] StringBuilder lpCharacter, uint nLength, COORD dwReadCoord,
    out uint lpNumberOfCharsRead);

[StructLayout(LayoutKind.Sequential)]
struct COORD
{
    public short X;
    public short Y;
}

Notes:

None.

private string ReadALineOfConsoleOutput()
{
    IntPtr stdout = GetStdHandle(STD_OUTPUT_HANDLE);

Tips & Tricks:

Please add some!

    if ( stdout.ToInt32() == INVALID_HANDLE_VALUE )
    throw new Win32Exception();

    // this assumes the console screen buffer is 80 columns wide.
    // You can call GetConsoleScreenBufferInfo() to get its actual dimensions.
    uint nLength = 80;    
    StringBuilder lpCharacter = new StringBuilder((int)nLength);

Sample Code:

    // read from the first character of the first line (0, 0).
    COORD dwReadCoord;
    dwReadCoord.X = 0;
    dwReadCoord.Y = 0;
    //Note #1: this isn't a complete program, but it's a lot better to start
    // from than nothing. There's so much stuff to set up here, the code sample
    // ends up getting pretty long in a hurry.

    uint lpNumberOfCharsRead = 0;
    //so, a call might look something like this
    //note: this reads a 3x3 block of characters around "Me".
    // could be used in a simple game, etc. (obviously, to
    // test this you're going to have to put it into a
    // class)

    if ( !ReadConsoleOutputCharacter(stdout, lpCharacter, nLength, dwReadCoord, out lpNumberOfCharsRead) )
    throw new Win32Exception();
    [DllImport("kernel32.dll")]
    static extern IntPtr GetStdHandle(int nStdHandle);

    return lpCharacter.ToString();
}
    [DllImport("kernel32.dll")]
    static extern bool ReadConsoleOutput(IntPtr hConsoleOutput, [Out] CHAR_INFO[]
       lpBuffer, COORD dwBufferSize, COORD dwBufferCoord,
       ref SMALL_RECT lpReadRegion);

    /*okay, now the actual code*/

Alternative Managed API:

Do you know one? Please contribute it!

    // Call kernel32.dll GetStdHandle to get a handle to the console's
     // STDOUT screen buffer (which we'll need so we can read the
     // stuff that's on the screen)
    IntPtr hStdOut;
    private const int STD_OUTPUT_HANDLE = -11;
     hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);

Documentation

     // we're going to read a 3x3 square buffer from the console.
     // so the buffer array needs to be 3 x 3 = 9 structs in size
     CHAR_INFO[] myCharInfo = new CHAR_INFO[9];

    //I just picked (4,5) as a good arbitrary center for reading
    short meX = 4;//pick an arbitrary column on the screen
    short meY = 5;//pick an arbitrary row on the screen

    //set up the dimensions of my buffer (3 by 3)
     COORD myBufferSize;
     myBufferSize.X = 3;
     myBufferSize.Y = 3;

     //set up where within the buffer to PUT what we read
    //(my buffer is only 3x3 and I'm reading a 3x3 square
    // so I better start writing to the buffer at 0,0 or
    // I'm going to overflow the buffer)
     COORD myBufferPosition;
     myBufferPosition.X = 0;
     myBufferPosition.Y = 0;

     //set up what part of the screen buffer to read.
    //(any Left, Right, Top, Bottom could be used. I just thought
    // this made an interesting example.)
     SMALL_RECT mySmallRect;
     mySmallRect.Left = (short)(meX - 1); //one space to the left of Me
     mySmallRect.Right = (short)(meX + 1); //one space to the right of Me
     mySmallRect.Top = (short)(meY - 1); //one space above me
     mySmallRect.Bottom = (short)(meY + 1); //one space below me

     //do the actual read of the screen buffer using
     // kernel32.dll's ReadConsoleOutput function
     ReadConsoleOutput(hStdOut, myCharInfo,
        myBufferSize, myBufferPosition,
        ref mySmallRect);

    //and now myCharInfo should be what we read. We can process that
    //however we like

Alternative Managed API:

Do you know one? Please contribute it!

(Sources at MSDN forums say there isn't one.)

Documentation

Please edit this page!

Do you have...

  • helpful tips or sample code to share for using this API in managed code?
  • corrections to the existing content?
  • variations of the signature you want to share?
  • additional languages you want to include?

Select "Edit This Page" on the right hand toolbar and edit it! Or add new pages containing supporting types needed for this API (structures, delegates, and more).

 
Access PInvoke.net directly from VS:
Terms of Use
Edit This Page
Find References
Show Printable Version
Revisions