2017-08-02 108 views
0

我在Java中是先进的,但在C#中是一个血腥的初学者。 我想我的意图很清楚: 我想在键盘上打印出'A'字符,但它不起作用:(我已经添加了PresentationCore.dll。 它是根本。对我来说,通过键盘,而不是控制台做到这一点提前为您的意见 由于这里是代码:C#键盘访问

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Runtime.InteropServices; 
using System.Text; 
using System.Threading; 
using System.Threading.Tasks; 
using System.Windows.Input; 

namespace ConsoleApp1 
{ 
class Program 
{ 

    static void Main(string[] args) 
    { 
    Console.WriteLine("This is a crappy programm, which doesn't work the way it is supposed to do!"); 
     while (true) 
     { 
      try 
      { 
       if (Keyboard.IsKeyDown(Key.A)) 
       { 
        Console.WriteLine("A is down! A is down!"); 
       } 
      } 
      catch (System.InvalidOperationException e) 
      { 

      } 
     } 
    } 
} 
} 
+0

“它不起作用” - 它做了什么,它应该做什么?你需要什么特别的帮助? – maccettura

+1

你看过KeyDown事件吗?正如我所提到的那样: – Yahtzee

+0

它应该打印出“A is down!A down!”只要'A'(键盘上的字符)关闭。 嗯,它不会尽快打印出行'A':) –

回答

1

的问题是,控制台应用程序有混乱的主线程是什么

将此属性放在您的static void Main(string[] args)之上:

[STAThread] 

这表示应用程序的COM线程模型是单线程单元或STA。

编辑:

还有,记得添加引用WindowsBase.dll,因为这是在Key枚举所在!

0
if (Console.KeyAvailable) 
{ 
    if (Console.ReadKey().Key == ConsoleKey.A) 
     Console.WriteLine("A is down! A is down!"); 
} 

而你现在不需要PresentationCore.dll。