簡體   English   中英

如何知道在 C++ 中使用 X11 的按鍵?

[英]How to know keypresses using X11 in C++?

我的目標:

我正在編寫C++程序,但缺少一些非常重要的東西,
程序需要知道按下了哪個鍵,但我不知道有什么方法可以做到。

問題:

經過一些研究,獲得按鍵的最原生方式似乎是使用X11
Xlib手冊中有關鍵盤輸入的所有內容都使用事件,
我不知道如何處理事件!

有沒有辦法在不使用事件的情況下知道按鍵?
或者如何使用X11事件?

如果需要任何說明,請添加評論或建議編輯

有兩種(和更多)方法可以實現它:

不推薦的硬方式

它具有所需的功能,但不推薦,因為它速度較慢且使用更多行代碼。

uint32_t PressedKeys[8];

bool RefreshPressedKeys() {
  while(XPending(X11Display)) {
    XEvent KeyEvent;
    XNextEvent(X11Display,&KeyEvent);
    if(KeyEvent.type==KeyPress) {
      uint32_t KeyEventCode=KeyEvent.xkey.keycode;
      for(uint8_t i=0;i<8;i++) {
        if(PressedKeys[i]==0) {
          PressedKeys[i]=KeyEventCode;
          break;
        }
      }
    }else if(KeyEvent.type==KeyRelease) {
      uint32_t KeyEventCode=KeyEvent.xkey.keycode;
      for(uint8_t i=0;i<8;i++) {
        if(PressedKeys[i]==KeyEventCode) {
          PressedKeys[i]=0;
          break;
        }
      }
    }
  }
  return true;
}

uint32_t GetAPressedKey() { //Get a pressed key, won't always the last pressed key
  for(uint8_t i=0;i<8;i++) {
    if(PressedKeys[i]!=0) return PressedKeys[i]; //Returns the first pressed key found
  }
  return 0; //Or 0 when no key found
}

bool IsKeyPressed(uint32_t KeyFilter) { //Is Key Pressed?
  for(uint8_t i=0;i<8;i++) {
    if(PressedKeys[i]==KeyFilter) return true; //Returns true if the key is pressed
  }
  return false; //Else false
}

int main() {
  uint8_t Key;
  XSelectInput(X11Display,X11Window,KeyPressMask|KeyReleaseMask); //Enables keyboard input
  while(1) {
    Key = GetPressedKey(); //Gets the pressed key's number
    std::cout << Key << '\n'; //Displays the number
    /* Some code using the Key var */
  }
  return 0;
}

推薦的簡單方法

該程序一開始可能更難理解,但它更好,因為它理論上可以處理一次按下的“無限”數量的鍵。

int main() {
  XSelectInput(Pixel.GetX11Display(),Pixel.GetX11Window(),KeyPressMask|KeyReleaseMask);
  while(1) {
    while(XPending(Pixel.GetX11Display())) { //Repeats until all events are computed
      XEvent KeyEvent;
      XNextEvent(Pixel.GetX11Display(),&KeyEvent); //Gets exactly one event
      if(KeyEvent.type==KeyPress) {
        uint32_t KeyEventCode=KeyEvent.xkey.keycode; //Gets the key code, NOT HIS CHAR EQUIVALENT
        std::cout << KeyEventCode << '\n'; //Displays the key code

        /* Code handling a Keypress event */

      } else if(KeyEvent.type==KeyRelease) {
         uint32_t KeyEventCode=KeyEvent.xkey.keycode;
         std::cout << KeyEventCode << '\n'; //Displays the key code

         /* Code handling a KeyRelease event */

      }
    }

    /* General code */

  }
}

這兩個代碼是我手寫的,我可能犯了錯誤,因為我沒有測試過,但應該是類似的。

論文是 copyleft,你不需要相信我 :)

請評論或建議對發現的任何錯誤或代碼澄清進行編輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM