我想从控制台窗口中特定位置的任何字符串中获取字符串值。例如,如果我在控制台屏幕上显示此内容:
abcdefgh
ijklmnop
qrstuvwx
我希望能够做到这样的事情:
string s = Console.GetString(1,2,4);
这将返回klmn
。这可能吗?
答案 0 :(得分:3)
从指定位置开始,从控制台屏幕缓冲区的连续单元格中复制多个字符。
示例:强>
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'
}
答案 1 :(得分:1)
您可以使用ReadConsoleOutput来指定阅读的坐标。
可在此处找到C#定义(包括示例):http://www.pinvoke.net/default.aspx/kernel32.readconsoleoutput