首页 > 解决方案 > 在终端中为 ncurses 启用鼠标事件

问题描述

在发表这篇文章之前,我已经查看了关于这个主题的几篇先前的文章,但是很难理解问题是什么,并且几乎没有运气让它适用于 WSL2。

到目前为止,我已经让它与 iTerm2 上的 ZSH 和 Mac 上的 VSCode 一起使用,使用该行printf("\033[?1003h)"允许我接收鼠标单击(右键单击除外)、滚动(向下滚动除外)和移动事件,其中鼠标在整个屏幕上跟踪移动。

对于 Windows 终端上的 WSL2 Ubuntu,使用相同的打印行允许我接收鼠标单击、鼠标滚动和移动事件,但是鼠标移动跟踪限制为 0 - 94 列。对于 VSCode 上的 WSL2 Ubuntu,我没有收到任何事件。

我真的很感激我能得到的任何帮助。

我一直用来测试的代码(不是我的代码):

#include <curses.h>
#include <stdio.h>
 
int main()
{
  initscr();
  cbreak();
  noecho();

  // Enables keypad mode. This makes (at least for me) mouse events getting
  // reported as KEY_MOUSE, instead as of random letters.
  keypad(stdscr, TRUE);

  // Don't mask any mouse events
  mousemask(ALL_MOUSE_EVENTS | REPORT_MOUSE_POSITION, NULL);

  // echo -e "\e[?1000;1006;1015h"
  printf("\033[?1003h\n"); // Makes the terminal report mouse movement events

  for (;;) { 
    int c = wgetch(stdscr);
 
    // Exit the program on new line fed
    if (c == '\n')
      break;
 
    char buffer[512];
    size_t max_size = sizeof(buffer);
    if (c == ERR) {
      snprintf(buffer, max_size, "Nothing happened.");
    }
    else if (c == KEY_MOUSE) {
      MEVENT event;
      if (getmouse(&event) == OK) {
        snprintf(buffer, max_size, "Mouse at row=%d, column=%d bstate=0x%08lx",
                 event.y, event.x, event.bstate);
      }
      else {
        snprintf(buffer, max_size, "Got bad mouse event.");
      }
    }
    else {
      snprintf(buffer, max_size, "Pressed key %d (%s)", c, keyname(c));      
    }
 
    move(0, 0);
    insertln();
    addstr(buffer);
    clrtoeol();
    move(0, 0);
  }
 
  printf("\033[?1003l\n"); // Disable mouse movement events, as l = low

  endwin();
 
  return 0;
}

标签: c++mouseeventncurses

解决方案


推荐阅读