flushconsoleinputbuffer (kernel32)
Last changed: Misto-170.218.219.22

.
Summary

C# Signature:

[DllImport("kernel32.dll")]
static extern bool FlushConsoleInputBuffer(IntPtr hConsoleInput);

User-Defined Types:

None.

Notes:

None.

Tips & Tricks:

Please add some!

Sample Code:

This code segment will allow you to grab the Console input buffer using CreateFileW and Flush the input using FlushConsoleInputBuffer

  [DllImport("kernel32.dll", SetLastError = true)]
  private static extern bool FlushConsoleInputBuffer(IntPtr hConsoleInput);

  [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint="CreateFileW")]
  private static extern IntPtr GetInputBuffer(
    MarshalAs(UnmanagedType.LPWStr)] string filename,
    [MarshalAs(UnmanagedType.U4)] UInt32 access,
    [MarshalAs(UnmanagedType.U4)] UInt32 share,
    IntPtr securityAttributes,
    [MarshalAs(UnmanagedType.U4)] UInt32 creationDisposition,
    [MarshalAs(UnmanagedType.U4)] UInt32 flagsAndAttributes,
    IntPtr templateFile);

  //C# method to flush console input
  public static void Flush()
  {
    //"CONIN$" will allow you to grab the input buffer regardless if it is being redirected.
    //0x40000000 | 0x80000000 - corresponds to GENERIC_READ | GENERIC_WRITE
    //0x00000001 - FILE_SHARE_READ - seems to be required to get the buffer correctly.
    //IntPtr.Zero - According to MSDN - "bInheritHandle member of the SECURITY_ATTRIBUTES structure must
    //be TRUE if the console is inherited"
    //if the console is not inherited, this can be null (IntPtr.Zero seen here)
    //3 - OPEN_EXISTING - recommended by MSDN to get the buffer correctly
    //The last two parameters are ignored in this case according to MSDN

    IntPtr inBuffer = GetInputBuffer("CONIN$", 0x40000000 | 0x80000000,
    0x00000001, IntPtr.Zero, 3, 0x0, IntPtr.Zero);

    //throw an error if the input buffer is not obtained
    Int32 error = Marshal.GetLastWin32Error();
    if (error != 0) throw new System.ComponentModel.Win32Exception(error);

    FlushConsoleInputBuffer(inBuffer);
  }

Alternative Managed API:

Do you know one? Please contribute it!

Documentation