gpt4 book ai didi

c# - 在不从缓冲区中删除其他按键的情况下拦截 ESC

转载 作者:太空宇宙 更新时间:2023-11-03 18:13:37 27 4
gpt4 key购买 nike

我有一个控制台应用程序可以提示用户进行多项输入。我希望用户能够在任何提示取消操作后按 Esc 键。

类似于:

if (Console.ReadKey().Key != ConsoleKey.Escape) {
string input = Console.ReadLine();
...
}

然而,这个问题是,如果按下除转义键以外的键,它将不会成为输入的一部分(从 ReadLine 返回)。

有没有办法“窥视”下一个键,或者以其他方式做到这一点?

最佳答案

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct InputRecord
{
internal short eventType;
internal KeyEventRecord keyEvent;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct KeyEventRecord
{
internal bool keyDown;
internal short repeatCount;
internal short virtualKeyCode;
internal short virtualScanCode;
internal char uChar;
internal int controlKeyState;
}

[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool PeekConsoleInput(IntPtr hConsoleInput, out InputRecord buffer, int numInputRecords_UseOne, out int numEventsRead);

[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool ReadConsoleInput(IntPtr hConsoleInput, out InputRecord buffer, int numInputRecords_UseOne, out int numEventsRead);

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

static Nullable<InputRecord> PeekConsoleEvent()
{
InputRecord ir;
int num;
if (!PeekConsoleInput(GetStdHandle(-10), out ir, 1, out num))
{
//TODO process error
}
if (num != 0)
return ir;
return null;
}
static InputRecord ReadConsoleInput()
{
InputRecord ir;
int num;
if (!ReadConsoleInput(GetStdHandle(-10), out ir, 1, out num))
{
//TODO process error
}
return ir;
}
static bool PeekEscapeKey()
{
for (; ; )
{
var ev = PeekConsoleEvent();
if (ev == null)
{
Thread.Sleep(10);
continue;
}
if (ev.Value.eventType == 1 && ev.Value.keyEvent.keyDown && ev.Value.keyEvent.virtualKeyCode == 27)
{
ReadConsoleInput();
return true;
}
if (ev.Value.eventType == 1 && ev.Value.keyEvent.keyDown)
return false;
ReadConsoleInput();
}
}

使用示例:

  for (; ; )
{
Console.Write("?");
if (PeekEscapeKey())
{
Console.WriteLine("esc");
continue;
}
Console.Write(">");
var line = Console.ReadLine();
Console.WriteLine(line);
}

关于c# - 在不从缓冲区中删除其他按键的情况下拦截 ESC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10342392/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com