1

我一直在玩 curses sharp 库(用于 pdcurses 的 ac# 包装器),编写了一些单元测试代码来了解 api 及其工作原理,我提出了一个问题。

我可以使用以下代码从 DLL 中快速运行 curses(以便 nUnit 可以测试它):

        bool consoleAllocated = AllocConsole();
        if (!consoleAllocated)
            throw new Exception("Unable to allocate a new console.");

        Curses.InitScr();

        Stdscr.Add(4, 6, "This is a test title");

        Curses.EndWin();

        FreeConsole();

AllocConsole 和 FreeConsole 是从 kernel32 导入的 extern。

我想做的是能够将控制台输出从位置 4,6 读取到字符串,以便以编程方式检查我输入的字符串是否已正确输出。例如,为了使用 TDD 创建一个 curses 风格的应用程序,能够进行这样的检查是非常重要的。

我查看了 Curses 和 Stdscr 对象(都是 Curses Sharp 对象)和 Console 对象(来自 windows 库),但还没有找到方法。有没有人有任何想法?

4

1 回答 1

3

我设法找到了答案,以防万一有人感兴趣,我已经包含了下面的代码。它很乱,因为我还没有清理它,但它应该作为如何做到这一点的一个例子。

感谢pinvoke.net提供的出色签名集。

    [DllImport("kernel32", SetLastError = true)]
    static extern bool AllocConsole();

    [DllImport("kernel32", SetLastError = true)]
    static extern bool FreeConsole();

    [DllImport("kernel32", SetLastError = true)]
    static extern IntPtr GetStdHandle(int nStdHandle);

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

    const int STD_OUTPUT_HANDLE = -11;

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

    [Test]
    public void WriteTitle()
    {
        bool consoleAllocated = AllocConsole();
        if (!consoleAllocated)
            throw new Exception("Unable to allocate a new console.");

        Curses.InitScr();

        Stdscr.Add(4, 6, "This is a test title");
        Stdscr.Refresh();

        IntPtr stdOut = GetStdHandle(STD_OUTPUT_HANDLE);
        uint length = 20;
        StringBuilder consoleOutput = new StringBuilder((int)length);
        COORD readCoord;
        readCoord.X = 6;
        readCoord.Y = 4;
        uint numOfCharsRead = 0;

        ReadConsoleOutputCharacter(stdOut, consoleOutput, length, readCoord, out numOfCharsRead);

        string outputString = consoleOutput.ToString();
        Assert.That(outputString, Is.EqualTo("This is a test title"));

        Curses.EndWin();

        FreeConsole();
    }
于 2011-07-21T01:52:59.423 回答