External Interfaces/API    

Writing Event Handlers

An event is fired when a control wants to notify its container that something of interest has occurred. For example, many controls trigger an event when the user single-clicks on the control. In MATLAB, you can create and register your own M-file functions so that they respond to events when they occur. These functions serve as event handlers. You can create one handler function to handle all events or a separate handler for each type of event.

Register your handler functions either at the time you create the control (using actxcontrol), or at any time afterwards (using registerevent). Specify the event handler in the argument list, as shown below for actxcontrol. The event handler argument can be either the name of a single callback routine or a cell array that associates specific events with their respective event handlers:

When you specify the single callback routine, MATLAB registers all events with that one routine. When any event is fired, MATLAB executes the common callback routine.

You can list all the events that a COM object recognizes using the events function. For example, to list all events for the mwsamp control, use

Arguments Passed to Event Handlers

When a registered event is triggered, MATLAB passes information from the event to its handler function as shown in this table.

Arguments Passed by MATLAB

Arg. No.
Object Name
MATLAB com class
Event ID
Start of Event Arg. List
As passed by the control
End of Event Arg. List (Arg. N)
As passed by the control
Event Structure
Event Name
char array

When writing an event handler function, use the Event Name argument to identify the source of the event. Get the arguments passed by the control from the Event Argument List (arguments 3 through end-2). All event handlers must accept a variable number of arguments:

Event Structure

The second to last argument passed by MATLAB is the Event Structure, which has the following fields.

Fields of the Event Structure

Field Name
Event Name
char array
Control Name

MATLAB com class

Event Identifier
Event Arg Name 1
Event Arg Value 1
As passed by the control
Event Arg Name 2
Event Arg Value 2
As passed by the control

For example, when the MouseDown event of the mwsamp control is triggered, MATLAB passes this Event Structure to the registered event handler:

Sample Event Handlers

Specify a single callback, sampev:

Or specify several events using the cell array format:

The event handlers, myclick.m, my2click.m, and mymoused.m, are

Alternatively, you can use the same event handler for all the events you want to monitor using the cell array pairs. Response time will be better than using the callback style.

For example:

where allevents.m is

  Releasing COM Interfaces and Objects Examples of MATLAB as an Automation Client