Mouse move not working when other application than MATLAB is open
6 views (last 30 days)
Show older comments
Hi all,
I am trying to click some buttons in another program than MATLAB with the function mousemove and keypress, see bottom description.
I am able to move my mouse when MATLAB is opened in my main window.
However, when i open a diffenrt application with MATLAB and try to move my mouse with the function mouseMove nothing happens.
I have the feeling that Java is not responding correct when MATLAB is not opened in my main window.
What could be the problem here?
mouse = Robot;
mouse.mouseMove(0, 0);
0 Comments
Answers (1)
Jack
on 22 Mar 2023
Hi,
It's possible that the issue is related to how the operating system handles input events when focus is on another window. By default, most operating systems restrict mouse and keyboard input to the foreground window for security reasons. This is known as "focus stealing prevention".
To ensure that your mouse movement and keypresses are sent to the correct window, you may need to bring the target window to the foreground before sending the input events. You can use the java.awt.Window method toFront() to bring a window to the front of the display stack. For example, you can use the following code to bring the active window to the front:
import java.awt.*;
import java.awt.event.*;
% get active window handle
activeWindow = java.awt.Window.getWindows();
activeWindow = activeWindow(end);
% bring window to front
activeWindow.toFront();
Once you have brought the target window to the front, you should be able to send mouse movements and keypresses to that window using the Robot class. For example, to move the mouse to a specific location in the target window, you can use:
mouse.mouseMove(targetX, targetY);
And to simulate a key press in the target window, you can use:
keyPress(KeyEvent.VK_A);
Note that you may need to import the KeyEvent class from the java.awt.event package to use the VK_A constant.
Thanks
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!