Search code examples
c#winapiconsole-applicationdllimportmanaged

Accessing GetConsoleHistoryInfo() from managed code


I've got a vaguely Java background and just installed Visual Studio Community 2015. Playing about with it so have a console app up and running and wanted to use above function after attaching to a different Console. Trouble is I have no idea about the appropriate declaration for this function - can someone tell me what it should be in this instance but also a good pointer for me in future so I can work it out on my own. The IDE doesn't seem to help much

using System.Runtime.InteropServices;

namespace ConsoleStuff
{
    class Program
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool GetConsoleHistoryInfo();

        static void Main(string[] args)
        {
                    GetConsoleHistoryInfo(); // <-- PInvokeStackImbalance occurred
        }
    }
}

Solution

  • You should declare it like this:

    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool GetConsoleHistoryInfo(ref CONSOLE_HISTORY_INFO ConsoleHistoryInfo);
    

    You will need the CONSOLE_HISTORY_INFO type too for this to work:

    [StructLayout(LayoutKind.Sequential)]
    public struct CONSOLE_HISTORY_INFO
    {
        uint cbSize;
        uint HistoryBufferSize;
        uint NumberOfHistoryBuffers;
        uint dwFlags;
    } 
    

    A lot of useful PInvoke information can be found at PInvoke.net. You should however double check it against the MSDN to see if it fits.