how to forbid several calls to the same function

1 回表示 (過去 30 日間)
Christophe
Christophe 2011 年 12 月 12 日
I have a function, myfun, which generates a user interface with several graphic objects. So, when I run myfun, I have still the possibility to enter commands in the MATLAB command window. How can I test if myfun is already running, in order to forbid a new call to myfun in the MATLAB command window ?

採用された回答

Jan
Jan 2011 年 12 月 12 日
During myfun create a GUI, you cannot enter new commands in Matlab's command window. But if myfun is ready, the prompt appears again and you can start myfun again.
You can set the Tag of the created figure uniquely and reject the processing of myfun is a figure with this tag is existing already.
function myfun
TagName = 'myUniqueTag_myfun';
existing = findobj(allchild(0), 'flat', 'Tag', TagName);
if ~isempty(existing)
figure(existing(1)); % bring figure to front
return;
end
figure('Name', 'myfun', 'Tag', TagName);
...
From an earlier discussion about timer objects I've learned, that this method can fail, if myfun is called from a callback of a timer. Then several figures can be created and using figure(existing(1)) is safer than using just figure(existing).
When you are using GUIDE to create the GUI, the option "GUI allows only one instance to run (singleton)" inserts similar code.
  1 件のコメント
Sean de Wolski
Sean de Wolski 2011 年 12 月 12 日
And the way GUIDE uses the singleton, is the call to openfig with the reuse option.

サインインしてコメントする。

その他の回答 (2 件)

Sean de Wolski
Sean de Wolski 2011 年 12 月 12 日
One way would be to save the figure and then use the openfig, with the reuse option.
doc openfig
  1 件のコメント
Jan
Jan 2011 年 12 月 12 日
The saved figure might not be compatible to older oder future versions of Matlab.

サインインしてコメントする。


Christophe
Christophe 2011 年 12 月 12 日
Thanks a lot Jan.

カテゴリ

Help Center および File ExchangeInteractive Control and Callbacks についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by