Linux: Capturing the mouse ala VirtualBox

How can a person "capture the mouse" ( in the same sense that vbox captures the mouse [1] )

in Linux using either C++ or C?

[1] In VBox ( essentially ) when you click on a vbox window, it captures the mouse in the sense that the mouse is constrained to the window. When pressing a key ( or some other event ) the mouse is free to return to the rest.


Edit: I was thinking in terms of Qt when I wrote this, which you may or may not be using. Something like this may work however in whatever gui framework you are using.

It doesn't appear that there is a single QWidget property you can set which would effect this. So what you'll have to do is 1) enable mouse tracking, 2) handle a mouse enter and/or focus event (within the QWidget), 3) Handle subsequent leave events, and when they occur 4) reset the mouse position to the nearest point within the widget using QCursor::setPos(), which is static. 2) and 3) would be taken care of with QWidget::enterEvent(), QWidget::focusInEvent(), and QWidget::leaveEvent().

I don't know if leave events are posted if the mouse is over the widget, but the widget isn't in focus; if not, then you can skip 2).


As I do not have concrete answer, I would like to recommend you, what I would do.

When there is a feature in opensource app, I'd recommend to play with it's sources.

If digging or reading is not enough, you might like to compile app with full debugging information and run under debugger to find piece of code responsible for interesting feature.

If you haven't been there, check out following places:

VirtualBox - Source code organization

VirtaulBox GUI frontend sources

Do some searches in chegesets like this, search for changesets with "mouse capture"

In changeset 30448 I see function call "captureMouse", I think that this or similar place might follow you to right piece of code.

What I've found, that might interest you most is:

src/VBox/Frontends/VirtualBox/src/runtime/UIMouseHandler.cpp Description: "FE/Qt4-OSX: Prevent the mouse from leaving the window in capture mode." , checkout these function:

void UIMouseHandler::captureMouse(ulong uScreenId)

To be complete, here is header file : UIMouseHandler.h

链接地址: http://www.djcxy.com/p/81002.html

上一篇: 编写一个AI:屏幕截图和输入

下一篇: Linux:捕获鼠标ala VirtualBox