C# 按键时切换布尔值

我目前有一个名为 debug 的 bool。我想要这样,当我按 F10 时,它会将 bool 设置为 true,然后如果我再次按回 false,依此类推。


这是我正在使用的代码:


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);

                }

            }

提前致谢。


慕姐8265434
浏览 332回答 2
2回答

Qyouu

bool debug = false;public void Toggle(){&nbsp; &nbsp; ConsoleKeyInfo keyinfo = Console.ReadKey();&nbsp; &nbsp; if (keyinfo.Key == ConsoleKey.F10)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; debug = !debug;&nbsp; &nbsp; &nbsp; &nbsp; if(debug)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//Your code here if debug = true&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//Your code here if debug = false&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //Your code here if key press other than F10&nbsp; &nbsp; }}ConsoleKeyInfo:描述按下的控制台键,包括控制台键所代表的字符以及 SHIFT、ALT 和 CTRL 修饰键的状态。尝试一次可能对你有帮助。

慕哥9229398

这取决于您想要的确切行为。您可能最好滚动自己的Console.WriteLine.以下切换debug并立即切换到其他模式,忽略任何部分输入的命令。private static bool InterruptableReadLine(out string result){&nbsp; &nbsp; var builder = new StringBuilder();&nbsp; &nbsp; var info = Console.ReadKey(true);&nbsp; &nbsp; while (info.Key != ConsoleKey.Enter && info.Key != ConsoleKey.F10)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Console.Write(info.KeyChar);&nbsp; &nbsp; &nbsp; &nbsp; builder.Append(info.KeyChar);&nbsp; &nbsp; &nbsp; &nbsp; info = Console.ReadKey(true);&nbsp; &nbsp; }&nbsp; &nbsp; Console.WriteLine();&nbsp; &nbsp; result = builder.ToString();&nbsp; &nbsp; return info.Key == ConsoleKey.F10;}// reading input, or just waiting for enter in your infinite loopstring command;var interrupted = InterruptableReadLine(out command);if (interrupted){&nbsp; &nbsp; debug = !debug;&nbsp; &nbsp; continue;}// do stuff with command if necessary
打开App,查看更多内容
随时随地看视频慕课网APP