(re)detect number of monitors connected when disconnecting monitor

Viewed 134

When multiple monitors are connected to my computer, I can detect them, and draw figures to them by setting the position according to the values obtained from

get(0, 'MonitorPositions')

However, when I disconnect a monitor while MATLAB is running, this property is not updated. I use distFig to handle the positioning of the figures, but since this property is not updated, sometimes the figures are drawn at the pixel locations that lay outside my screen (i.e. drawing on my disconnected monitor).

Restarting MATLAB solves the issue, but is there a way to re-detect the number of monitors connected?

1 Answers

I think I found a solution using JAVA:

I got the JAVA code from here: How do I get number of available screens?

Getting number of

get(0, 'MonitorPositions') keeps showing the same value, and the JAVA result changes:

%// Get local graphics environment
%GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
env = java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment();

%// Returns an array of all of the screen GraphicsDevice objects.
%GraphicsDevice[] devices = env.getScreenDevices();
devices = env.getScreenDevices();

%numberOfScreens = devices.length;
numberOfScreens = length(devices)

I tested the code in Windows 10 OS.
In monitor duplicate mode, result is one monitor, and in extended mode 2.
When I unplug a monitor, the result is 1.
When unplugging all monitors the result is also 1 (it's not a perfect solution).

Related