2017-08-02 150 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。