0

我想从控制台窗口上特定位置的任何字符串中获取字符串值。例如,如果我在控制台屏幕上有这个:

abcdefgh
ijklmnop
qrstuvwx

我希望能够做类似的事情:

string s = Console.GetString(1,2,4);

这将返回klmn。这可能吗?

4

2 回答 2

3

使用ReadConsoleOutputCharacter

从控制台屏幕缓冲区的连续单元格中复制多个字符,从指定位置开始。


例子:

private const int STD_OUTPUT_HANDLE = -11;

public static string GetString(Int16 y, Int16 x, uint length)
{
    var characters = new StringBuilder(1);
    uint numberOfCharactersRead;

    if (ReadConsoleOutputCharacter(GetStdHandle(STD_OUTPUT_HANDLE), characters, length,  new Coord(x, y), out numberOfCharactersRead))
        return characters.ToString();

    throw new InvalidOperationException("Could not get chars");
}

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

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool ReadConsoleOutputCharacter(IntPtr hConsoleOutput, [Out] StringBuilder lpCharacter, uint length, Coord bufferCoord, out uint lpNumberOfCharactersRead);

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

    public Coord(short x, short y)
    {
        X = x;
        Y = y;
    }
}

用法:

static void Main(string[] args)
{
    Console.WriteLine("abcdefgh");
    Console.WriteLine("ijklmnop");
    Console.WriteLine("qrstuvwx");

    string s = GetString(1, 2, 4);
    // 's' is now 'klmn'
}
于 2013-02-12T14:09:47.397 回答
1

您可以使用ReadConsoleOutput,它允许您指定读取的坐标。

C# 定义可以在这里找到(包括一个例子):http ://www.pinvoke.net/default.aspx/kernel32.readconsoleoutput

于 2013-02-12T13:48:50.817 回答