我为了好玩而尝试学习编程(如果我弄错了术语,请提前道歉),并发现了一个我正在努力解决的问题。我一直在尝试让一个程序与按键交互(例如:你按下“空格键”,控制台将打印"hello world"),但无法获得交互的事件和方法。
我做错了什么?是我错过了一个简单的步骤,还是我把结构完全搞错了?
谢谢!
代码
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;
}
}
}
}
}发布于 2015-11-18 04:22:43
从这个开始:
public bool dKey_KeyDown()
{
var key = Console.ReadKey();
if (key == ConsoleKey.D)
{
return true;
}
else
{
return false;
}
} 发布于 2015-11-18 04:23:01
您发布的代码根本不起作用。
首先,您在不带任何参数的情况下调用dKey_KeyDown,但是此方法的声明需要两个参数:object sender和KeyEventArgs e...so。代码甚至不会编译,更不用说运行了。
其次,看起来您可能从Windows Forms coding中的一些示例代码中复制并粘贴了这段代码;在本例中,sender和e由窗体代码提供,作为其事件处理机制的一部分。我不会在这里详细介绍,但它不会在控制台中工作application..you可以阅读有关它的更多信息here
为了方便起见,这里有一个简单的程序,它使用Console.ReadKey
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");
}
}
}最后-祝贺你决定开始编程!坚持下去,你会很高兴你做到了:)
https://stackoverflow.com/questions/33766109
复制相似问题