How can I get the character at the cursor in a C# console application?

杀马特。学长 韩版系。学妹 提交于 2019-12-07 21:17:23

问题


I know how to set the cursor to a specific point in the console with SetCursorPosition or CursorLeft and CursorTop together. That's not a problem.

But, how can I get the value of that point? Isn't there a thing like Console.Cursor? So I can get the character at that position? Maybe something like:

char c = Console.GetCharAtCursor();

No luck?


回答1:


AFAIK, you have to read the entire console buffer as a two dimensional buffer, and use the cursor's X and Y coordinates as an index into that buffer. See:

[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
public static extern bool GetConsoleScreenBufferInfo(
    IntPtr consoleHandle,
    out CONSOLE_SCREEN_BUFFER_INFO consoleScreenBufferInfo);

You can read about the buffer structure here:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms682093(v=vs.85).aspx

Update:

If you're interested in using console APIs for game writing, someone wrote space invaders for the console (actually powershell) but all of the APIs are managed code, not script. He has sprite/path routines etc - the source is over on http://ps1.soapyfrog.com/2007/08/26/grrr-source-code-including-invaders/




回答2:


'CursorLeft' and 'CursorTop' have getters so you can just read them: var cleft = Console.CursorLeft




回答3:


According the answer from the MSDN forum:

[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 static char ReadCharacterAt(int x, int y)
{
    IntPtr consoleHandle = GetStdHandle(-11);
    if (consoleHandle == IntPtr.Zero)
    {
        return '\0';
    }
    COORD position = new COORD
    {
        X = (short)x,
        Y = (short)y
    };
    StringBuilder result = new StringBuilder(1);
    uint read = 0;
    if (ReadConsoleOutputCharacter(consoleHandle, result, 1, position, out read))
    {
        return result[0];
    }
    else
    {
        return '\0';
    }
}

Applied it looks like this:

class Program
{
    static void Main(string[] args)
    {
        Console.Clear();

        Console.CursorLeft = 0;
        Console.CursorTop = 1;
        Console.Write("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");

        char first = ReadCharacterAt(10, 1);
        char second = ReadCharacterAt(20, 1);

        Console.ReadLine();
    }
}


来源:https://stackoverflow.com/questions/9790280/how-can-i-get-the-character-at-the-cursor-in-a-c-sharp-console-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!