C#按键时切换布尔值

C#按键时切换布尔值,c#,C#,我现在有一个叫做debug的bool。我想要它,这样当我按下F10时,它会将布尔设置为真,然后如果我再次按下它,它就会返回到假,依此类推 这是我正在使用的代码: bool debug = false; if (cVersion < oVersion) { Process.Start("http://consol.cf/update.php"); return; } for (;

我现在有一个叫做debug的bool。我想要它,这样当我按下F10时,它会将布尔设置为真,然后如果我再次按下它,它就会返回到假,依此类推

这是我正在使用的代码:

bool debug = false;
        if (cVersion < oVersion)
        {
            Process.Start("http://consol.cf/update.php");
            return;
        }
        for (; ; )
        {
            if (debug)
            {
                Console.WriteLine("Please type in a command");
                cmd = Console.ReadLine();
                p.Send(cmd);
            }
            else
            {
                Console.WriteLine("Press enter to execute config");
                Console.ReadLine();
                WebConfigReader conf =
                new WebConfigReader(url);
                string[] tokens = Regex.Split(conf.ReadString(), @"\r?\n|\r");
                foreach (string s in tokens)
                //ConsoleConfig cons = new ConsoleConfig();
                {
                    p.Send(s);
                    //p.Send(test);
                }
            }
bool debug=false;
if(cVersion
提前谢谢

bool debug = false;

public void Toggle()
{
    ConsoleKeyInfo keyinfo = Console.ReadKey();

    if (keyinfo.Key == ConsoleKey.F10)
    {
        debug = !debug;
        if(debug)
        {
           //Your code here if debug = true
        }
        else
        {
           //Your code here if debug = false
        }
    }
    else
    {

        //Your code here if key press other than F10
    }
}
ConsoleKeyInfo:描述按下的控制台键,包括控制台键表示的字符以及SHIFT、ALT和CTRL修改键的状态


尝试一次可能会对您有所帮助。

这取决于您想要的确切行为。您最好使用自己版本的
控制台。WriteLine

以下切换
debug
并立即切换到其他模式,忽略任何部分输入的命令

private static bool InterruptableReadLine(out string result)
{
    var builder = new StringBuilder();
    var info = Console.ReadKey(true);

    while (info.Key != ConsoleKey.Enter && info.Key != ConsoleKey.F10)
    {
        Console.Write(info.KeyChar);
        builder.Append(info.KeyChar);
        info = Console.ReadKey(true);
    }

    Console.WriteLine();
    result = builder.ToString();

    return info.Key == ConsoleKey.F10;
}

// reading input, or just waiting for enter in your infinite loop
string command;
var interrupted = InterruptableReadLine(out command);
if (interrupted)
{
    debug = !debug;
    continue;
}
// do stuff with command if necessary

@Lazarus Holl,请查看答案可能对你有帮助:)@Lazarus Holl,我更新了答案视图一次可能对你有帮助:)