2013-03-18 96 views
3

如何在C中跟蹤Linux中的鍵盤或鼠標事件?在linux上使用C跟蹤鍵盤和鼠標事件

像例如,如果用戶按ESC移位等我應該能夠跟蹤它。鼠標的方法相同。如果用戶移動鼠標或向左或向右點擊。

實現的想法是創建一個帶定時器的小屏幕保護程序,並且我正在努力如何跟蹤鍵盤或鼠標事件來重置定時器。

回答

2

一種可能性是使用輸入子系統。 看一看這篇文章:使用輸入子系統(http://www.linuxjournal.com/article/6429

另一個是創建一個工作線程,嘗試讀取文件/ dev/input/event *這裏可以看到鍵盤:

// (const char *)ptr - pass your device like "/dev/input/event2" here 
fd = open((const char *)ptr, O_RDONLY); 

if (fd < 0) 
{ 
    fprintf(stderr, "failed to open input device %s: %s\n", (const char *)ptr, strerror(errno)); 
    return NULL; 
} 

struct timeval escapeDown = { 0, 0}; 
int code; 
while (1) 
{ 
    if (read(fd, &ev, sizeof(struct input_event)) < 0) 
    { 
     fprintf(stderr, "failed to read input event from input device %s: %s\n", (const char *)ptr, strerror(errno)); 
     if (errno == EINTR) 
      continue; 
     break; 
    } 

    code = -1; 
    if (ev.type == EV_KEY) 
    { 
     switch (ev.code) 
     { 
     case eEsc: 
      if (ev.value == 1) 
      { 
       escapeDown = ev.time; 
       printf("DOWN: ESC\n"); 
      } 
      else if (ev.value == 0 && escapeDown.tv_sec) 
      { 
       printf("UP: ESC\n"); 
       if (isLongPressed(&escapeDown, &ev.time)) 
        code = eEscLong; 
       else 
        code = eEsc; 

       escapeDown.tv_sec = 0; 
       escapeDown.tv_usec = 0; 
      } 
      break; 
     case eOk: 
     case eUp: 
     case eRight: 
     case eLeft: 
     case eDown: 
      if (ev.value == 0) 
      { 
       printf("UP: %s\n", keyName(ev.code)); 
       code = ev.code; 
      } 
      else if (ev.value == 1) 
      { 
       printf("DOWN: %s\n", keyName(ev.code)); 
      } 
      escapeDown.tv_sec = 0; 
      escapeDown.tv_usec = 0; 
      break; 
     default: 
      break; 
     } 
    } 
    if (code > 0) 
    { 
     struct sMsg* pMsg = malloc(sizeof(struct sMsg)); 
     if (pMsg) 
     { 
      pMsg->nMsgType = eMsgKeyLogger; 
      pMsg->nIntValue= code; 
      postMsg(pMsg); 
     } 
     printf("generated keyboard event: %u %s\n", 
       code, 
       keyName(code)); 
    } 
    else 
     usleep(100); 
} 

close(fd); 
+0

由於這將是有用的我,但我要如何檢查哪個文件是鍵盤?因爲對於總是在/ dev/input/mouse0或/ dev/input/mouse中的鼠標,變化正在發生,但是如果對於鍵盤它發生在/ dev/input/event1或event 4等每當我更換鍵盤或重新啓動機器時。所以有沒有辦法找到哪個文件只負責鍵盤和鼠標只有系統系統啓動了 – 2013-03-18 09:34:13

+0

您可以嘗試所有/ dev/input/event *或查看/var/log/Xorg.0.log您的鍵盤使用哪種設備。 – duDE 2013-03-18 09:53:56

1

考慮到項目的規模和性質,你可能想看看GLUT。它實際上是一個OpenGL的便利庫,但也提供了易於使用的跨平臺輸入處理和計時器功能。以防萬一您想在將來轉移到其他平臺。除此之外,它與您的應用程序的圖形性質完美融合。

編輯:我鏈接的項目實際上是原始GLUT的繼承者,具有整體增強的API。有關原始API參考,請看here

在你的情況,你可以使用類似:

void keyboardFunc(unsigned char key, int x, int y) 
{ 
    switch (key) 
    { 
    case 'a': 
     break; 
    /* etc */ 
    } 
} 

void displayFunc() 
{ 
    /* Statements issuing the drawing of your screensaver */ 
} 

int main(int argc, char** argv) 
{ 
    glutInit(&argc, argv); 

    /* Other initialization code */ 

    glutKeyboardFunc(keyboardFunc); 
    glutDisplayFunc(displayFunc); 

    glutMainLoop(); 
}