Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine MATLAB's Monitor in a multiple monitor configuration

I move around from a company site to another a lot. At any given day, I might have just my laptop or as many as four monitors. With multiple monitors, I don't know which monitor I will choose to use for MATLAB main GUI (the main GUI launched when double-clicking matlab.exe). It depends on the resolutions of the available monitors.

I use scripts that utilize programmatically generated GUIs (not by GUIDE) and it seems that MATLAB pops them up always on the first monitor. I've researched a little bit and found to locate the GUIs to a monitor of choice by using p = get(gcf, 'Position'), set(0, 'DefaultFigurePosition', p), and movegui command, but this will only work if I know beforehand which monitor I want to use.

Is there a way to find out on which monitor the main MATLAB GUI is up and have other little GUIs pop up on the same monitor?

like image 465
Eric Avatar asked Jun 08 '16 14:06

Eric


1 Answers

We can use some Java tricks to get the current monitor; see code with comments below:

function mon = q37705169
%% Get monitor list:
monitors = get(groot,'MonitorPositions'); % also get(0,'MonitorPositions');
%% Get the position of the main MATLAB screen:
pt = com.mathworks.mlservices.MLEditorServices.getEditorApplication.getActiveEditor.getComponent.getRootPane.getLocationOnScreen;
matlabScreenPos = [pt.x pt.y]+1; % "+1" is to shift origin for "pixel" units.
%% Find the screen in which matlabScreenPos falls:
mon = 0;
nMons = size(monitors,1);
if nMons == 1
  mon = 1;
else
  for ind1 = 1:nMons    
    mon = mon + ind1*(...
      matlabScreenPos(1) >= monitors(ind1,1) && matlabScreenPos(1) < sum(monitors(ind1,[1 3])) && ...
      matlabScreenPos(2) >= monitors(ind1,2) && matlabScreenPos(2) < sum(monitors(ind1,[2 4])) );
  end
end

Few notes:

  • Root properties documentation.
  • An output value of "0" means that something's wrong.
  • There may be an easier way to get the "RootPane"; I've used a method with which I have good experience.
  • This will only recognize one of the monitors in case your MATLAB window spans several monitors. If this functionality is required you can use com.mathworks.mlservices.MLEditorServices.getEditorApplication.getActiveEditor.getComponent.getRootPane.getWidth etc. to find the other corners of the MATLAB window and do the same test with them.
  • I didn't bother with breaking out of the loop after the first valid monitor was found since it is assumed that: 1) Only one monitor is valid. 2) The overall amount of monitors the loop will have to process is small.
  • For the brave, one can perform a check with polygons (i.e. inpolygon).
like image 60
Dev-iL Avatar answered Oct 06 '22 09:10

Dev-iL