C#窗体如何在每次按下键盘键时运行方法

本文关键字:键盘 方法 运行 窗体 | 更新日期: 2023-09-27 18:20:08

我的代码在WindowsConsoleApplication 中运行良好

// The below code is working in WindowsConsoleApplication
class Class1
{
    public int a = 0;
    static void Main(string[] args)
        {
            Program prg = new Program();
            prg.hell(); 
            Console.WriteLine("Working" + prg.a);
            Console.ReadKey();
        }
    public void hell()
        {
            Console.WriteLine("Press any key to stop");
            while
                (!Console.KeyAvailable || Console.ReadKey(true).Key != ConsoleKey.DownArrow )
            { 
                a += 1;
            }
        }
}

但是当我尝试在C#窗体中使用hell方法时,会抛出一个错误

// This code isn't working in C# windows form
class Class1
{
    public int a = 0;
    public void hell()
        {
            Console.WriteLine("Press any key to stop");
            while 
                (!Console.KeyAvailable || Console.ReadKey(true).Key != ConsoleKey.DownArrow)
            {
                a += 1;
            } 
        }
}
private void Form1_Load(object sender, EventArgs e)
{
    Class1 obj = new Class1();
    MessageBox.Show("WORKING....");
    obj.hell();
    MessageBox.Show("Isn't Working...." + obj.a);
}

obj.hell()抛出错误

当应用程序没有控制台或当控制台输入已从文件重定向时。尝试Console.In.Peek.

我该如何解决这个问题?请试着编译代码看看发生了什么,我尝试了线程,但它们没有帮助。工作代码将比解释更有帮助。我也尝试了Form1_KeyDown,但它抛出了相同的错误。

C#窗体如何在每次按下键盘键时运行方法

错误消息告诉您真相。Windows应用程序没有控制台,因此通常不能使用任何控制台方法。要在每次按下Windows应用程序中的键时运行一个方法,请查看Form对象上的KeyPress事件。我认为您的想法是正确的,但请确保"控制台"一词不会出现在事件处理程序中的任何位置。