首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何让方法和KeyEventArgs相互交互?

如何让方法和KeyEventArgs相互交互?
EN

Stack Overflow用户
提问于 2015-11-18 04:12:40
回答 2查看 76关注 0票数 0

我为了好玩而尝试学习编程(如果我弄错了术语,请提前道歉),并发现了一个我正在努力解决的问题。我一直在尝试让一个程序与按键交互(例如:你按下“空格键”,控制台将打印"hello world"),但无法获得交互的事件和方法。

我做错了什么?是我错过了一个简单的步骤,还是我把结构完全搞错了?

谢谢!

代码

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace Key_Input_2
{
    class MainProgram
    {
        static void Main(string[] args)
        {
            KeyInput_2 k = new KeyInput_2();
            bool keyType = k.dKey_KeyDown();

            if (keyType == true)
            {
            Console.WriteLine("Hello World");
            }
        }
    }


    class KeyInput_2
    {

        bool dKey = false;

        public bool dKey_KeyDown(object sender, KeyEventArgs e)
        {
            while (dKey == false)
            {
                if (e.KeyCode == Keys.D)
                {
                    return true;
                }

                else
                {
                    return false;
                }

            }
        }        
    }
}
EN

回答 2

Stack Overflow用户

发布于 2015-11-18 04:22:43

从这个开始:

代码语言:javascript
复制
public bool dKey_KeyDown()
{
  var key = Console.ReadKey();
  if (key == ConsoleKey.D)
  {
    return true;
  }
  else
  {
     return false;
  }
}        
票数 0
EN

Stack Overflow用户

发布于 2015-11-18 04:23:01

您发布的代码根本不起作用。

首先,您在不带任何参数的情况下调用dKey_KeyDown,但是此方法的声明需要两个参数:object senderKeyEventArgs e...so。代码甚至不会编译,更不用说运行了。

其次,看起来您可能从Windows Forms coding中的一些示例代码中复制并粘贴了这段代码;在本例中,sendere由窗体代码提供,作为其事件处理机制的一部分。我不会在这里详细介绍,但它不会在控制台中工作application..you可以阅读有关它的更多信息here

为了方便起见,这里有一个简单的程序,它使用Console.ReadKey

代码语言:javascript
复制
using System;

namespace SimpleKey
{
    class Program
    {
        static void Main(string[] args)
        {
            //make a variable to store the input from the user's keypress
            ConsoleKeyInfo input = new ConsoleKeyInfo();
            //keep executing the code inside the block ({..}) until the user presses the Spacebar
            while (input.Key != ConsoleKey.Spacebar)
            {
                Console.WriteLine("Press SpaceBar...");
                input = Console.ReadKey();
            }
            //now they have pressed spacebar, so display the message
            Console.WriteLine("Hello World");
        }
    }
}

最后-祝贺你决定开始编程!坚持下去,你会很高兴你做到了:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33766109

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档