2

我正在开发一个控制台应用程序,我需要在其中检测几个热键,例如Ctrl+ NCtrl+OCtrl+ S。这是我用来识别这些热键的部分代码:

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上面的代码对+NCtrl+没有任何问题O。但是,我无法让它为Ctrl+工作S。在做了一些快速测试之后,我发现按下Ctrl+S甚至什么都没有做(这意味着程序仍在等待用户输入某些内容)。

此问题仅发生在Ctrl+S上。对任何其他修饰符(例如)和键(,等)使用一些简单if的语句都可以正常工作。ShiftNO

为什么会这样?Ctrl+S组合有什么特殊含义吗?有可能完成这项工作吗?如果是,如何?

4

2 回答 2

0

ThreeStarProgrammer57的帮助下,我为自己的控制台应用程序提出了这个解决方案。

您需要使用SetConsoleMode配置控制台并传递" ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT | ENABLE_EXTENDED_FLAGSasSuggested 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

于 2019-11-05T08:38:18.317 回答
0
protected override  bool  ProcessCmdKey(ref Message msg, Keys keyData)
{
    if (msg.Msg == 256)
    {
        //if the user pressed control + s
        if (keyData == (Keys.Control | Keys.S))
        {

        }
        //if the user pressed control + o 
        else if (keyData == (Keys.Control | Keys.O))
        {

        }
        //if the user pressed control + n 
        else if (keyData == (Keys.Control | Keys.N))
        {

        }
    }
    return base.ProcessCmdKey(ref msg, keyData);
}
于 2017-02-04T07:54:56.027 回答