How to close one or all currently open Matlab (*.m) files from Matlab command prompt?

前端 未结 2 1505
情歌与酒
情歌与酒 2021-01-19 07:47

I found a solution on the web (see below, circa 2009) which does not work on my machine (Windows 7, Matlab R2013a):

Editor = com.mathworks.mlservices.MLEdito         


        
2条回答
  •  逝去的感伤
    2021-01-19 08:41

    The following seems to work. I've tested in Matlab R2014b, Windows 7 64 bits.

    1. Acccess the editor Java object.
    2. Get the number of open documents, say D.
    3. Programmatically make the editor the window in front.
    4. Programmatically send ALT-F4 keystrokes D times to close all open files. Optionally, send also N keystrokes D times in case some file is not saved and you want to close it (i.e. reply "no" when the editor asks if you want to save it). If the file is already saved, sending an N causes no harm.

    For step 1 I found inspiration in this post. For steps 2 and 3 I inspected the methods of the editor object until I found something interesting. For step 4 I took the procedure I used in this answer, which in turn was based on this information.

    Code:

    closeUnsaved = 1; %// 1 if you want to close even if documentds are not saved
    %// Step 1:
    desktop = com.mathworks.mde.desk.MLDesktop.getInstance;
    jEditor = desktop.getGroupContainer('Editor').getTopLevelAncestor; %// editor object
    %// Step 2:
    D = jEditor.getGroup.getDocumentCount;
    %// Step 3:
    jEditor.requestFocus; %// make editor the window in front
    %// Step 4:
    robot = java.awt.Robot;
    for n = 1:D
        robot.keyPress (java.awt.event.KeyEvent.VK_ALT); %// press "ALT"
        robot.keyPress (java.awt.event.KeyEvent.VK_F4); %// press "F4"
        robot.keyRelease (java.awt.event.KeyEvent.VK_F4); %// release "F4"
        robot.keyRelease (java.awt.event.KeyEvent.VK_ALT); %// release "ALT"
        if closeUnsaved
            robot.keyPress (java.awt.event.KeyEvent.VK_N); %// press "N"
            robot.keyRelease (java.awt.event.KeyEvent.VK_N); %// release "N"
        end
    end
    

提交回复
热议问题