控制台:检查Keypress(Esc)

时间:2015-12-03 08:24:15

标签: c#

在你标记之前,我已经尝试了几种解决方案(我发誓它不重复)并最终导致VS崩溃的错误。

编辑:有人说我的循环不起作用。问题不存在,它与按键有关 enter image description here

这是我的原始代码:

        while (true)
            {
                Console.WriteLine("Voer een getal in : ");
                string invoer = Console.ReadLine();
                Console.Write("Voer de macht in waarmee u wilt vermenigvuldigen :");
                string macht = Console.ReadLine();

                int getal = Convert.ToInt32(invoer);
                int getalmacht = Convert.ToInt32(macht);

                int uitkomst = (int)Math.Pow(getal, getalmacht);
                Console.WriteLine("De macht van " + getal + " is " + uitkomst + " .");
                Console.ReadLine();


            }

它工作正常,但它没有寻找按键。

这是一个检查按键并且不会抛出错误的文件:

namespace Democonsole
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Press ESC to stop.");

        do
        {
            while (!Console.KeyAvailable)
            {

                Console.WriteLine("Voer een getal in : ");
                string invoer = Console.ReadLine();
                Console.Write("Voer de macht in waarmee u wilt vermenigvuldigen :");
                string macht = Console.ReadLine();

                int getal = Convert.ToInt32(invoer);
                int getalmacht = Convert.ToInt32(macht);

                int uitkomst = (int)Math.Pow(getal, getalmacht);
                Console.WriteLine("De macht van " + getal + " is " + uitkomst + " .");
                Console.ReadLine();


            }
        } while (Console.ReadKey(true).Key != ConsoleKey.Escape);




    }
}

}

然而,它会在运行崩溃时发生,并在printcreen中显示错误。

还有其他方法吗?

编辑:添加了我尝试过的解决方案的更多示例。

    static void Main(string[] args)
{
    var myWorker = new MyWorker();
    myWorker.DoStuff();
    Console.WriteLine("Press any key to stop...");
    Console.ReadKey();
}

断裂

     while (true)
                    {
                        Console.WriteLine("Voer een getal in : ");
                        string invoer = Console.ReadLine();
                        Console.Write("Voer de macht in waarmee u wilt vermenigvuldigen :");
                        string macht = Console.ReadLine();

                        int getal = Convert.ToInt32(invoer);
                        int getalmacht = Convert.ToInt32(macht);

                        int uitkomst = (int)Math.Pow(getal, getalmacht);
                        Console.WriteLine("De macht van " + getal + " is " + uitkomst + " .");
                        Console.ReadLine();
                        Console.Keypress()



`

2 个答案:

答案 0 :(得分:2)

错误消息告诉您几乎所有关于错误的信息,即您尝试将字符串转换为整数并且字符串无法转换为整数。可能是因为它是空的。

这只是问题的一部分,我将在稍后讨论。

首先,你的循环结构是错误的。只要没有等待读取的按键,内循环就会运行。但是在循环体的末尾,你明确地清除了控制台缓冲区的内容,所以永远不会退出内循环。

考虑这个最小的例子:

while (!Console.KeyAvailable)
{
    Console.ReadLine();
}

假设在遇到while语句(将跳过整个事件)时没有等待读取的键,内部语句将累积按键中的字符,直到您按Enter键然后将字符作为字符串返回。几微秒后,它将检查你是否在输入后按下了另一个键,这实际上是不可能的。因此,这是编写无限循环的一种奇怪方式。

下一个问题是您要求用户输入并假设输入有效。它不是,这是导致你之前获得的那些例外的原因。总是假设用户要输入你的程序没有预料到的东西,并弄清楚如何处理它出错。

例如:

string invoer = Console.ReadLine();
int getal;
if (!int.TryParse(invoer, out getal))
{
    Console.WriteLine("Invalid value '{0}'", invoer);
    continue;
}

如果该值未转换为数字,则会抱怨它并返回循环的开头。如果值为空,您可能还想尝试退出循环:

string invoer = Console.ReadLine();
if (string.IsNullOrEmpty(invoer))
    break;
int getal;
if (!int.TryParse(invoer, out getal))
{
    Console.WriteLine("Invalid value '{0}'", invoer);
    continue;
}

这至少可以让你摆脱循环,这是你目前没有的。

答案 1 :(得分:0)

我使用以下解决方案有一个完全替代的解决方案。标题sais,你想要esc检查。所以这就是。高度复制自this solution

ConsoleHoKeyManager.cs>

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Threading;

namespace ConsoleHotKey
{
    public static class HotKeyManager
    {
        public static event EventHandler<HotKeyEventArgs> HotKeyPressed;

        public static int RegisterHotKey(Keys key, KeyModifiers modifiers)
        {
            _windowReadyEvent.WaitOne();
            int id = System.Threading.Interlocked.Increment(ref _id);
            _wnd.Invoke(new RegisterHotKeyDelegate(RegisterHotKeyInternal), _hwnd, id, (uint)modifiers, (uint)key);
            return id;
        }

        public static void UnregisterHotKey(int id)
        {
            _wnd.Invoke(new UnRegisterHotKeyDelegate(UnRegisterHotKeyInternal), _hwnd, id);
        }

        delegate void RegisterHotKeyDelegate(IntPtr hwnd, int id, uint modifiers, uint key);
        delegate void UnRegisterHotKeyDelegate(IntPtr hwnd, int id);

        private static void RegisterHotKeyInternal(IntPtr hwnd, int id, uint modifiers, uint key)
        {
            RegisterHotKey(hwnd, id, modifiers, key);
        }

        private static void UnRegisterHotKeyInternal(IntPtr hwnd, int id)
        {
            UnregisterHotKey(_hwnd, id);
        }

        private static void OnHotKeyPressed(HotKeyEventArgs e)
        {
            if (HotKeyManager.HotKeyPressed != null)
            {
                HotKeyManager.HotKeyPressed(null, e);
            }
        }

        private static volatile MessageWindow _wnd;
        private static volatile IntPtr _hwnd;
        private static ManualResetEvent _windowReadyEvent = new ManualResetEvent(false);
        static HotKeyManager()
        {
            Thread messageLoop = new Thread(delegate()
            {
                Application.Run(new MessageWindow());
            });
            messageLoop.Name = "MessageLoopThread";
            messageLoop.IsBackground = true;
            messageLoop.Start();
        }

        private class MessageWindow : Form
        {
            public MessageWindow()
            {
                _wnd = this;
                _hwnd = this.Handle;
                _windowReadyEvent.Set();
            }

            protected override void WndProc(ref Message m)
            {
                if (m.Msg == WM_HOTKEY)
                {
                    HotKeyEventArgs e = new HotKeyEventArgs(m.LParam);
                    HotKeyManager.OnHotKeyPressed(e);
                }

                base.WndProc(ref m);
            }

            protected override void SetVisibleCore(bool value)
            {
                // Ensure the window never becomes visible
                base.SetVisibleCore(false);
            }

            private const int WM_HOTKEY = 0x312;
        }

        [DllImport("user32", SetLastError = true)]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

        [DllImport("user32", SetLastError = true)]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        private static int _id = 0;
    }


    public class HotKeyEventArgs : EventArgs
    {
        public readonly Keys Key;
        public readonly KeyModifiers Modifiers;

        public HotKeyEventArgs(Keys key, KeyModifiers modifiers)
        {
            this.Key = key;
            this.Modifiers = modifiers;
        }

        public HotKeyEventArgs(IntPtr hotKeyParam)
        {
            uint param = (uint)hotKeyParam.ToInt64();
            Key = (Keys)((param & 0xffff0000) >> 16);
            Modifiers = (KeyModifiers)(param & 0x0000ffff);
        }
    }

    [Flags]
    public enum KeyModifiers
    {
        Alt = 1,
        Control = 2,
        Shift = 4,
        Windows = 8,
        NoRepeat = 0x4000,
        None = 0
    }
}

的Program.cs&GT;

using ConsoleHotKey;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Democonsole
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Press ESC to stop.");
            HotKeyManager.RegisterHotKey(Keys.Escape, KeyModifiers.None);
            HotKeyManager.HotKeyPressed += new EventHandler<HotKeyEventArgs>(Console_CancelKeyPress);
            while (true)
            {
                Console.WriteLine("Voer een getal in : ");
                string invoer = Console.ReadLine();
                Console.Write("Voer de macht in waarmee u wilt vermenigvuldigen :");
                string macht = Console.ReadLine();

                int getal = Convert.ToInt32(invoer);
                int getalmacht = Convert.ToInt32(macht);

                int uitkomst = (int)Math.Pow(getal, getalmacht);
                Console.WriteLine("De macht van " + getal + " is " + uitkomst + " .");
                Console.ReadLine();
            }
        }

        static void Console_CancelKeyPress(object sender, HotKeyEventArgs e)
        {
            Environment.Exit(0);
        }
    }
}

你也必须引用system.windows.forms。