MATLAB AI Chat Playground solved this problem for me. Following is its answer.
MATLAB does not have a built-in way to determine whether it is running in the background or in the foreground. However, you can use the desktop function to check whether the MATLAB desktop is running. If the desktop is running, then MATLAB is likely running in the foreground. If the desktop is not running, then MATLAB is likely running in the background.
if desktop('-inuse')
disp('MATLAB is running in the foreground.')
else
disp('MATLAB is running in the background.')
end
Note that this method may not work in all cases, as the `desktop` function may not be available in some MATLAB configurations.