调用Gpm_Open()后终端打印鼠标事件乱码的原因及解决方法
Gpm_Getc()? Let's break down what's happening and how to fix it:
The Root Cause
When you call Gpm_Open() with conn.eventMask = 0, libgpm falls back to a default behavior: it forwards raw mouse event escape sequences directly to your program's standard output. Those weird ^[[M ... characters you see are console-native mouse event codes, but since gnome-terminal is a pseudoterminal emulator, it can't interpret them properly, so they show up as garbage.
Even if you don't call Gpm_Getc() to read events, GPM still sends these escape sequences to stdout because your connection configuration tells it you aren't planning to capture events programmatically.
The Fix: Configure libgpm to Capture Events Instead of Forwarding
You need to explicitly set an event mask to tell libgpm you want to handle mouse events in your code—this disables the default stdout forwarding. Here's the modified version of your code:
#include <gpm.h> #include <stdio.h> int main(int argc, char *argv[]) { Gpm_Connect conn; // Set the mask to capture the events you care about (adjust as needed) conn.eventMask = GPM_DOWN | GPM_UP | GPM_MOVE; conn.defaultMask = GPM_DOWN | GPM_UP; // Default for unhandled event cases conn.minMod = 0; conn.maxMod = ~0; if (Gpm_Open(&conn, 0) == -1) { printf("Cannot connect to mouse server\n"); return 1; } // Optional: Add this loop later if you want to read and handle events // Gpm_Event event; // while (Gpm_GetEvent(&event) != -1) { // /* Process mouse events here */ // } while (1); // Keep the program running Gpm_Close(); return 0; }
Key Changes:
conn.eventMaskis set to specific event types (GPM_DOWNfor clicks,GPM_UPfor releases,GPM_MOVEfor mouse movement) instead of0. This tells libgpm to send these events to your program instead of dumping them to stdout.conn.defaultMaskis narrowed down to relevant events (tweak this based on your actual needs).
Additional Notes for Pseudoterminals (gnome-terminal)
Since you're using gnome-terminal instead of a real console:
- Sometimes terminal emulators have their own mouse handling that might conflict with GPM. If you still see issues, try disabling mouse reporting in gnome-terminal's settings (look for options like "Allow mouse reporting").
- Ensure the GPM daemon is running (
sudo systemctl start gpm)—most modern Linux setups handle pseudoterminal compatibility by default, but double-check if you run into connection issues.
内容的提问来源于stack exchange,提问作者Luke 10X

