2017-01-10 85 views
0

我有在C#中相當一個問題,現在我試圖代碼時按F8鍵被按下檢測功能,並設置布爾F8Pushed爲true,那麼當它再次按下設定F8Pushed爲false。如何當一個鍵被按下一個布爾變量設置爲true和false時,它再次推?

這裏是我的代碼至今:

static bool IsKeyPressed() //This Function Returns True if F8 Is Pushed and False if F8 is up 
{ 
    bool is_pressed = (GetAsyncKeyState(119) & 0x8000) != 0; 
    return is_pressed; 
} 

static void CheckHotKey() //This is the Function that I am calling the other function from for debugging. 
{ 
    while (true) 
    { 
     Console.WriteLine(IsKeyPressed()); 
    } 
} 

現在,我有和無法解決的問題是,我不能找到一個辦法讓變量自身複製到另一個變量,並如果有意義的話,能夠回到錯誤。我可以得到一個布爾值設置爲true,如果IsKeyPressed() == true但我無法弄清楚如何得到它回false時,它再次返回true。

在此先感謝!

編輯: 感謝您的幫助傢伙但是我仍然有一些麻煩,下面有一個更新。

static bool IsKeyPressed() 
    { 
     is_pressed = (GetAsyncKeyState(119) & 0x8000) != 0 && !is_pressed; 
     return is_pressed; 
    } 

    static void CheckHotKeys() 
    { 
     while (true) 
     { 
      IsKeyPressed(); 
      if(is_pressed) 
      { 
       F8Pushed = true; 
      } 
      Console.WriteLine(F8Pushed); 
      if(IsKeyPressed()) 
      { 
       F8Pushed = false; 
      } 
      Console.WriteLine(F8Pushed); 
     } 
    } 

我設法得到它的工作有點不過,它是非常錯誤和很多次關鍵中風沒有檢測到任何想法?

+0

看起來你已經寫了一個無限循環與你而(真)。該變量永遠不會改變,因爲線程永遠不會離開這個循環。 – Mishax

+0

但我可以調用其他功能,可以改變它的權利? – user3885393

回答

1

我不確定我是否完全理解了什麼你正在努力完成。您的代碼包含了許多問題的部分,我選擇寫一個完全新的代碼:指定鍵的

class Program 
{ 
    const byte VK_F8 = 0x77; 
    const byte VK_ESC = 0x1b; 

    static bool globalAppState = false; 

    static void Main(string[] args) 
    { 
    bool lastState = IsKeyPressed(VK_F8); 
    while (!IsKeyPressed(VK_ESC)) 
    { 
     bool newState = IsKeyPressed(VK_F8); 
     if (lastState != newState) 
     { 
     if (newState) 
     { 
      Console.WriteLine("F8: pressed"); 
      globalAppState = !globalAppState; 
     } 
     else 
      Console.WriteLine("F8: released"); 
     lastState = newState; 
     } 
    } 
    } 

    static bool IsKeyPressed(byte keyCode) 
    { 
    return ((GetAsyncKeyState(keyCode) & 0x8000) != 0); 
    } 

    [DllImport("user32.dll")] 
    static extern short GetAsyncKeyState(int vKey); 
} 

功能IsKeyPressed(VK_F8)告訴你總是當前狀態(按下/釋放)。

當您只需要在更改(從按下到發佈,或從發佈到按下)時執行一些操作用您的特定任務替換控制檯輸出功能。

當你需要一些多線程就像在一個新的線程處理事件,這是一個不同的問題......(此範圍內)

編輯:變量對每個新添加的關鍵變化按下的事件。這是骯髒的解決方案...

0

你不得不做出這樣的變量is_pressed全球,以保持目前的狀態。然後作出這樣的嘗試:

static bool is_pressed; 
static bool IsKeyPressed() 
{ 
    is_pressed = (GetAsyncKeyState(119) & 0x8000) != 0 && !is_pressed; 
    return is_pressed; 
} 

&& !is_pressed每次都會

0

切換的價值爲你假設你存儲在一個布爾值的按鍵結果:

bool isKeyPressed = true; 

你可以這樣做:

isKeyPressed == IsKeyPressed() && !isKeyPressed; 
相關問題