2017-07-29 129 views
-1

編輯2017 07 30 13:49 這與其他問題的主要區別在於: 如何檢測2按下按鍵同一時間?C#,控制檯,如何檢查按鍵是否被按下,並相應地實時更改變量

例如:只有在同時按下按鍵A和按鍵B時纔在屏幕上顯示「2」的程序。當A或B或兩者都釋放時,它顯示「1」

以下程序不起作用,因爲ReadKey需要等待。

if(Console.KeyAvailable){}也不起作用,因爲它只允許讀取一個密鑰,而不是如果同時按下多個鍵。

總之,我希望有人能告訴我,在使用時,立刻就出去放一個布爾值的函數是否取決於是否被按下而不讓程序的某些關鍵的等待

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

namespace ConsoleApp9 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      int number = 2; 
      while (true) 
      { 
       Console.Clear(); 

       if (Console.ReadKey(true).Key == ConsoleKey.B & Console.ReadKey(true).Key == ConsoleKey.A) 
       { 
        Console.Write(2); 
       } 
       else 
       { 
        Console.Write(1); 
       } 
      } 
     } 
    } 
} 

我是新到C#現在我想知道是否有辦法檢查是否按下了鍵,並相應地實時更改變量。

我有一個程序在鍵被按下後輸出一個數字,但是,它的更新速度太慢,一次只能檢查一個鍵。 (如果我同時按AB,它只能識別A或B.)

是否有一個輸出布爾值並且不會像Console.ReadKey()那樣阻止代碼的函數? (或類似的東西)例如,如果在使用此功能時按下A,「功能(A)」將輸出「真」。如果不是的話,它會輸出一個「假」,然後程序進入下一行。

總之,你能告訴我如何編程一個控制檯,以便它有一個反映實時按鍵的變量列表嗎?

(使用while(true)循環,在任何時候,我按下按鍵A.程序寫入變量科亞= true時,它不隨時按下,科亞= FALSE)

試過事件,但不能讓它工作。 (編譯期間「不存在」錯誤)

這是我正在使用的程序。

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


namespace ConsoleApp9 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      int number = 2; 
      while (true) 
      { 
       if (Console.KeyAvailable) 
       { 
        var key = Console.ReadKey(); 
        Console.Write((int)key.KeyChar); 
       } 
      } 
     } 
    } 
} 
+4

2分鐘內出現類似問題。 https://stackoverflow.com/questions/45393158/detecting-single-key-presses-in-console-c-sharp –

+0

你不能使用ReadKey或者任何控制檯方法。您必須以其他方式檢查按鍵狀態,如果您沒有使用winform或wpf系統(大多數情況下會爲您處理),則很可能使用P/Invoke。 –

回答

0

看到這個代碼:

class Program 
{ 
    [System.Runtime.InteropServices.DllImport("User32.dll")] 
    public static extern short GetAsyncKeyState(int vKey); 

    static void Main(string[] args) 
    { 
     while (GetAsyncKeyState('Q') == 0) 
     { 
      short result = GetAsyncKeyState('A'); 
      if (result < 0 && (result & 0x01) == 0x01) 
       Console.WriteLine("A pressed and up"); 
     } 
    } 
} 

按下Q退出或A看到的是被按下的消息。您還可以使用GetKeyboardState API一次檢索所有密鑰的信息。請務必閱讀文檔以正確理解返回值和使用情況。

+0

非常感謝!這個功能正是我需要的。 – ian

相關問題