MATLAB: How to force execution of the ClickFcn callback of a Simulink annotation object every time I update the block diagram

simulink

I have annotation objects in my Simulink model with ClickFcn callback code such as the following:
annotationObject = getCallbackAnnotation;
annotationObject.Text = [gcs ' : ' annotationObject.Text];
The code executes as expected when I click on the annotation. However, I would also like the same code to be automatically executed every time I update the block diagram on a model-wide basis for all annotation blocks. In other words, I would like to imitate the InitFcn callback that is available for library blocks.

Best Answer

The ability to execute a callback for an annotation object when the block diagram is updated is not available in Simulink.
Simulink.Annotation objects are data objects and do not have an InitFcn callback associated with them, as for Simulink library blocks.
In order to work around this issue, evaluate the ClickFcn code in the model's InitFcn callback, by using the Simulink.Annotation objects' ClickFcn property as follows:
annotationHandles = find_system(gcs, 'FindAll', 'on', 'type', 'annotation');
for annotationIndex = 1:length(annotationHandles)
annotationObject = get_param(annotationHandles(annotationIndex), 'Object');
eval(annotationObject.ClickFcn)
end
However, note that the callback code is executed in the base workspace. Therefore, operations (such as GETCALLBACKANNOTATION) that depend on being invoked from the annotation callback do not behave as expected.
In cases where GETCALLBACKANNOTATION is used, the entire callback code must be implemented in the InitFcn callback as follows:
annotationHandles = find_system(gcs, 'FindAll', 'on', 'type', 'annotation');
for annotationIndex = 1:length(annotationHandles)
annotationObject = get_param(annotationHandles(annotationIndex), 'Object');
annotationObject.Text = [gcs ' : ' annotationObject.Text];
end