MATLAB: How to programmatically bring an App to the foreground of the screen via the Callback Function of a Push Button in another App

MATLAB

I have an app (built with appdesigner) that, upon pressing a button, opens another app (also built in appdesigner) – let's call them appA and appB. The first time the button is pressed, appB opens and runs forever (unless I explicitly close the window in which it lives). 
Assume that after I open appB, I continue working with appA.  Then, at some point, I press the button again.  Since appB is already running, all I want is to bring appB to the front so that I can interact with it.  How can I achieve this programmatically in the button callback function?
In summary, I would like to implement the following workflow programmatically:
1) First, call an App ("appB") from within another App ("appA") upon pressing a Push Button.
2) At a later time, bring the same App, "appB", back to the foreground of your screen via the Callback Function of the same Push Button in "appA".

Best Answer

One method of accomplishing this is detailed below:
Step 1)
Create a property for "appA" to which you will assign the object instantiated when you call "appB".  For example, let "appBHandle" be the property name.  For now, initialize it as an empty array.  You can adapt the following example code:
properties (Access = private)
appBHandle = [];
end
Step 2)
In the Callback Function for the Push Button, check if "appBHandle" is either...
a) empty, which is true the first time the Push Button is pressed
b) an invalid handle, which is true when the Push Button is pressed after the object has been deleted (i.e. after "appB" has been closed)
If so, then call the function "appB" (to open the App and its associated UI Figure), and assign the object that is instantiated to the variable/property "appBHandle".
If not, then "appBHandle" can be utilized to bring "appB" to the foreground of your screen.   This is done by toggling the visibility property of the UI Figure for "appB" off and then immediately back on.
You can adapt the following example code into the Callback Function for your Push Button:
function ButtonPushed(app, event)
if isempty(app.appBHandle) || ~isvalid(app.appBHandle) %used if "appB" either has not been called or has been closed
app.appBHandle = appB;
else %used if "appB" is open
app.appBHandle.UIFigure.Visible = 'off';
app.appBHandle.UIFigure.Visible = 'on';
end
end