在ThreeStarProgrammer57的帮助下,我为自己的控制台应用程序提出了这个解决方案。
您需要使用SetConsoleMode配置控制台并传递" ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT | ENABLE_EXTENDED_FLAGS
asSuggested by oconnor0"。
导入所需的内核函数:
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
[Flags]
private enum ConsoleInputModes : uint
{
ENABLE_PROCESSED_INPUT = 0x0001,
ENABLE_LINE_INPUT = 0x0002,
ENABLE_ECHO_INPUT = 0x0004,
ENABLE_WINDOW_INPUT = 0x0008,
ENABLE_MOUSE_INPUT = 0x0010,
ENABLE_INSERT_MODE = 0x0020,
ENABLE_QUICK_EDIT_MODE = 0x0040,
ENABLE_EXTENDED_FLAGS = 0x0080,
ENABLE_AUTO_POSITION = 0x0100
}
[Flags]
private enum ConsoleOutputModes : uint
{
ENABLE_PROCESSED_OUTPUT = 0x0001,
ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002,
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004,
DISABLE_NEWLINE_AUTO_RETURN = 0x0008,
ENABLE_LVB_GRID_WORLDWIDE = 0x0010
}
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nStdHandle);
static int STD_INPUT_HANDLE = -10;
并在您的程序中使用它们,如下所示:
// Add this section to your code:
SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), (uint)(
ConsoleInputModes.ENABLE_WINDOW_INPUT |
ConsoleInputModes.ENABLE_MOUSE_INPUT |
ConsoleInputModes.ENABLE_EXTENDED_FLAGS
));
// ------------------------------
ConsoleKeyInfo input = Console.ReadKey(true);
if (input.Modifiers == ConsoleModifiers.Control)
{
if (input.Key == ConsoleKey.N)
{
// ...
}
else if (input.Key == ConsoleKey.O)
{
// ...
}
else if (input.Key == ConsoleKey.S)
{
//...
}
}
该解决方案不仅可以让您捕捉Ctrl+S击键,还可以捕捉Ctrl+ C!