首页 > 解决方案 > C# 在按键时切换布尔值

问题描述

我目前有一个名为 debug 的 bool。我想要它,这样当我按下 F10 时,它会将布尔值设置为 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);
                }
            }

提前致谢。

标签: c#

解决方案


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修饰键的状态。

试一次可能对你有帮助。


推荐阅读