Contents

Use Events

About Events

An event is typically a user-initiated action that takes place in a server application, which often requires a reaction from the client. For example, a user clicking the mouse at a particular location in a server interface window might require the client take some action in response. When an event is fired, the server communicates this occurrence to the client. If the client is listening for this particular type of event, it responds by executing a routine called an event handler.

The MATLAB® COM client can subscribe to and handle the events fired by a Microsoft® ActiveX® control or a COM server. Select the events you want the client to listen to by registering each event you want active with the event handler to be used in responding to the event. When a registered event takes place, the control or server notifies the client, which responds by executing the appropriate event handler routine. You can write event handlers as MATLAB functions.

    Note:   MATLAB does not support asynchronous events.

    Note:   MATLAB does not support interface events from a Custom server.

Functions for Working with Events

Use the MATLAB functions in the following table to register and unregister events, to list all events, or to list just registered events for a control or server.

FunctionDescription

actxcontrol

Create a COM control and optionally register those events you want the client to listen to

eventlisteners

Return a list of events attached to listeners

events

List all events, both registered and unregistered, a control or server can generate

isevent

Determine if an item is an event of a COM object

registerevent

Register an event handler with a control or server event

unregisterallevents

Unregister all events for a control or server

unregisterevent

Unregister an event handler with a control or server event

Event names and event handler names are not case sensitive. You cannot abbreviate them.

Examples of Event Handlers

The following examples use event handlers:

Responding to Events — an Overview

This section describes the basic steps to handle events fired by a COM control or server.

Identifying All Events

Use the events function to list all events the control or server can respond to. This function returns a structure array, where each field of the structure is the name of an event handler, and the value of that field contains the signature for the handler routine. To invoke events on an object with handle h, type:

S = events(h)

Registering Those Events You Want to Respond To

Use the registerevent function to register those server events you want the client to respond to. You can register events as follows:

  • If you have one function to handle all server events, register this common event handler using the syntax:

    registerevent(h,'handler')
  • If you have a separate event handler function for different events, use the syntax:

    registerevent(h.{'event1' 'handler1'; 'event2' 'handler2';})

For ActiveX controls, you can register events at the time you create an instance of the control using the actxcontrol function.

  • To register a common event handler function to respond to all events, use:

    h = actxcontrol('progid', position, figure, 'handler');
  • To register a separate function to handle each type of event, use:

    h = actxcontrol('progid', position, figure, ...
       {'event1' 'handler1'; 'event2' 'handler2'; ...});

The MATLAB client responds only to events you have registered. If you register the same event name to the same callback handler multiple times, MATLAB executes the event only once.

Identifying Registered Events

The eventlisteners function lists only currently registered events. This function returns a cell array, with each row representing a registered event and the name of its event handler. For example, to invoke eventlisteners on an object with handle h, type:

C = eventlisteners(h)

Responding to Events As They Occur

Whenever a control or server fires an event that the client is listening for, the client responds to the event by invoking one or more event handlers that have been registered for that event. You can implement these routines as MATLAB functions. Read more about event handlers in the section on Writing Event Handlers.

Unregistering Events You No Longer Want to Listen To

If you have registered events that you now want the client to ignore, you can unregister them at any time using the functions unregisterevent and unregisterallevents as follows:

  • For a server with handle h, to unregister all events registered with a common event handling function handler, use:

    unregisterevent(h,'handler')
  • To unregister individual events eventN, each registered with its own event handling function handlerN, use:

    unregisterevent(h,{'event1' 'handler1'; 'eventN' 'handlerN'})
  • To unregister all events from the server regardless of which event handling function they are registered with, use:

    unregisterallevents(h)

Responding to Events — Examples

The following examples show you how to respond to events from different COM objects:

Responding to Events from an ActiveX Control

This example describes how to handle events fired by an ActiveX control. It uses a control called mwsamp2 that ships with MATLAB.

Tasks described in this section are:

Creating Event Handler Routines.  You can view the event handler code for the mwsamp2 control in the section Sample Event Handlers. Create the event handler files myclick.m, my2click.m, and mymoused.m and save them on your path, for example, c:\work.

Creating a Control and Registering Events.  The actxcontrol function not only creates the control object, but you can use it to register specific events, as well. The code shown here registers two events (Click and MouseDown) and two respective handler routines (myclick and mymoused) with the mwsamp2 control:

f = figure('position', [100 200 200 200]);
ctrl = actxcontrol('mwsamp.mwsampctrl.2', [0 0 200 200], f, ...
    {'Click','myclick'; 'MouseDown','mymoused'});

If, at some later time, you want to register additional events, use the registerevent function. For example:

registerevent(ctrl,{'DblClick','my2click'})

Unregister the DblClick event before continuing with the example:

unregisterevent(ctrl,{'DblClick','my2click'})

Listing Control Events.  At this point, only the Click and MouseDown events should be registered. To list all events, whether registered or not, type:

objEvents = events(ctrl)
objEvents = 
         Click: 'void Click()'
      DblClick: 'void DblClick()'
     MouseDown: 'void MouseDown(int16 Button, int16 Shift, Variant x, Variant y)'
    Event_Args: 'void Event_Args(int16 typeshort, int32 typelong, double typedou...'

This function returns a structure array, where each field of the structure is the name of an event handler and the value of that field contains the signature for the handler routine. For example:

objEvents.Event_Args
ans =
   void Event_Args(int16 typeshort, int32 typelong,  
        double typedouble, string typestring, bool typebool)

To list only the currently registered events, use the eventlisteners function:

eventlisteners(ctrl)
ans = 
    'click'        'myclick' 
    'mousedown'    'mymoused'

This function returns a cell array, with each row representing a registered event and the name of its event handler.

Responding to Control Events.  When MATLAB creates the mwsamp2 control, it also displays a figure window showing a label and circle at the center. If you click different positions in this window, you see a report in the MATLAB Command Window of the X and Y position of the mouse.

Each time you press the mouse button, the MouseDown event fires, calling the mymoused function. This function prints the position values for that event to the Command Window. For example:

The X position is: 
ans = 
    [122]
The Y position is: 
ans = 
    [63]

The Click event displays the message:

Single click function

Double-clicking the mouse does nothing different, since the DblClick event is not registered.

Unregistering Control Events.  When you unregister an event, the client discontinues listening for occurrences of that event. When the event fires, the client does not respond. If you unregister the MouseDown event, MATLAB no longer reports the X and Y positions. Type:

unregisterevent(ctrl,{'MouseDown' 'mymoused'})

When you click in the figure window, MATLAB displays:

Single click function

Now, register the DblClick event, using the my2click event handler:

registerevent(ctrl,{'DblClick', 'my2click'})

If you call eventlisteners again:

eventlisteners(ctrl)

MATLAB displays:

ans = 
    'click'       'myclick' 
    'dblclick'    'my2click'

When you double-click the mouse button, MATLAB displays:

Single click function
Double click function

An easy way to unregister all events for a control is to use the unregisterallevents function.

unregisterallevents(ctrl)
eventlisteners(ctrl)

When there are no events registered, eventlisteners returns an empty cell array:

ans = 
     {}

Clicking the mouse in the control window now does nothing since there are no active events.

Using a Common Event Handling Routine.  If you have events that are registered with a common event handling routine, such as sampev.m used in the following example, you can use unregisterevent to unregister all of these events in one operation. This example first registers all events from the server with a common handling routine sampev.m. MATLAB now handles any type of event from this server by executing sampev:

registerevent(ctrl,'sampev')

Verify the registration by listing all event listeners for that server:

eventlisteners(ctrl)

MATLAB displays:

ans = 
    'click'        'sampev'
    'dblclick'     'sampev'
    'mousedown'    'sampev'

Now unregister all events for the server that use the sampev event handling routine:

unregisterevent(ctrl,'sampev')
eventlisteners(ctrl)

MATLAB displays:

ans = 
     {}

Close the figure window.

Responding to Events from an Automation Server

This example shows how to handle events fired by an Automation server. It creates a server running the Microsoft Internet Explorer® program, registers a common event handler for all events, and then has you fire events by browsing to Web sites.

Tasks described in this section are:

Creating an Event Handler.  Register all events with the same handler routine, serverevents. Create the file serverevents.m, inserting the following code. Make sure that the file is in your current folder.

function serverevents(varargin)

% Display incoming event name
eventname = varargin{end}

% Display incoming event args
eventargs = varargin{end-1}

Creating a Server.  Next, at the MATLAB command prompt, type the following commands:

% Create a server running Internet Explorer.
browser = actxserver('internetexplorer.application');
% Make the server application visible.
set(browser,'Visible', 1);

Listing Server Events.  Use the events function to list all events the server can respond to, and eventlisteners to list the registered events:

events(browser)

MATLAB displays event information like:

        :
StatusTextChange = void StatusTextChange(string Text)
ProgressChange = void ProgressChange(int32 Progress,int32 ProgressMax)
CommandStateChange = void CommandStateChange(int32 Command,bool Enable)
        :  

List the registered events:

eventlisteners(browser)

No events are registered at this time, so MATLAB displays:

ans = 
      {} 

Registering Server Events.  Now use your event handler serverevents.

registerevent(browser,'serverevents')
eventlisteners(browser)

MATLAB displays:

ans = 
             :                     :
    'statustextchange'      'serverevents'
    'progresschange'        'serverevents'
    'commandstatechange'    'serverevents'
             :                     :

Responding to Server Events.  At this point, all events have been registered. If any event fires, the common handler routine defined in serverevents.m executes to handle that event. Use the Internet Explorer software to browse your favorite Web site, or enter the following command in the MATLAB Command Window:

Navigate2(browser,'http://www.mathworks.com');

You should see a long series of events displayed in the Command Window.

Unregistering Server Events.  Use the unregisterevent function to unregister the progresschange and commandstatechange events:

unregisterevent(browser,{'progresschange', 'serverevents'; ...
   'commandstatechange', 'serverevents'})

To unregister all events for an object, use unregisterallevents. The following commands unregister all the events that had been registered, and then registers a single event:

unregisterallevents(browser)
registerevent(browser,{'TitleChange', 'serverevents'})

If you now use the Web browser, MATLAB only responds to the TitleChange event.

Closing the Application.  Close a server application when you no longer intend to use it. To unregister all events and close the application, type:

unregisterallevents(browser)
Quit(browser);
delete(browser);

Responding to Interface Events from an Automation Server

This example, demonstrating how to handle a COM interface event, shows how to set up an event in a Microsoft Excel® workbook object and how to handle its BeforeClose event.

To create the event handler OnBeforeCloseWorkbook, create the file OnBeforeCloseWorkbook.m, inserting the following code. Make sure that the file is in your current folder:

% Event handler for Excel workbook BeforeClose event 
function OnBeforeCloseWorkbook(varargin)
    disp('BeforeClose event occurred');

When you run the following commands:

% Create Excel automation server instance
xl = actxserver('Excel.Application');
% Make it visible
xl.Visible = 1;

% Get collection of workbooks and add a new workbook
hWbks = xl.Workbooks;
hWorkbook = hWbks.Add;

% Register OnClose event
registerevent(hWorkbook,{'BeforeClose' @OnBeforeCloseWorkbook})

% Close the workbook. This fires the Close event 
% and calls the OnClose handler
Close(hWorkbook)

MATLAB displays:

BeforeClose event occurred

Writing Event Handlers

This section covers the following topics on writing handler routines to respond to events fired from a COM object:

Overview of Event Handling

An event is fired when a control or server wants to notify its client that something of interest has occurred. For example, many controls trigger an event when the user clicks somewhere in the interface window of a control. Create and register your own MATLAB functions to respond to events when they occur. These functions are event handlers. You can create one handler function to handle all events or a separate handler for each type of event.

For controls, you can register handler functions either at the time you create an instance of the control (using actxcontrol), or at any time afterwards (using registerevent).

Both actxcontrol and registerevent use an event handler argument. 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. Strings used in the event handler argument are not case sensitive.

For servers, use registerevent to register those events you want the client to listen to. For example, to register the Click and DblClick events, use:

registerevent(h,{'click','myclick'; 'dblclick','my2click'})

Use events to list all the events a COM object recognizes. For example, to list all events for the mwsamp2 control, use:

f = figure('position',[100 200 200 200]);
h = actxcontrol('mwsamp.mwsampctrl.2',[0 0 200 200],f);

h.events
   Click = void Click()
   DblClick = void DblClick()
   MouseDown = void MouseDown(int16 Button, int16 Shift,  
      Variant x, Variant y)

Arguments Passed to Event Handlers

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

Arguments Passed by MATLAB Functions

Arg. No.ContentsFormat

1

Object name

MATLAB COM class

2

Event ID

double

3

Start of Event Argument List

As passed by the control

end-2

End of Event Argument List (Argument N)

As passed by the control

end-1

Event Structure

structure

end

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:

function event (varargin)
if (strcmp(varargin{end}, 'MouseDown'))  % Check the event name
    x_pos = varargin{5};              % Read 5th Event Argument
    y_pos = varargin{6};              % Read 6th Event Argument
end

    Note:   The values passed vary with the particular event and control being used.

Event Structure

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

Fields of the Event Structure

Field NameDescriptionFormat

Type

Event Name

char array

Source

Control Name

MATLAB COM class

EventID

Event Identifier

double

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

etc.

Event Arg N

As passed by the control

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

    Type: 'MouseDown'
  Source: [1x1 COM.mwsamp.mwsampctrl.2]
 EventID: -605
  Button: 1
   Shift: 0
       x: 27
       y: 24

Sample Event Handlers

Specify a single callback, sampev:

f = figure('position',[100 200 200 200]);
h = actxcontrol('mwsamp.mwsampctrl.2',[0 0 200 200],gcf,'sampev')
h =
    COM.mwsamp.mwsampctrl.2

Or specify several events using the cell array format:

h = actxcontrol('mwsamp.mwsampctrl.2', [0 0 200 200],f,... 
    {'Click','myclick'; 'DblClick','my2click'; ... 
    'MouseDown','mymoused'});

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

function myclick(varargin)
disp('Single click function')

function my2click(varargin)
disp('Double click function')

function mymoused(varargin)
disp('You have reached the mouse down function')
disp('The X position is: ')
double(varargin{5})
disp('The Y position is: ')
double(varargin{6})

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

For example:

f = figure('position',[100 200 200 200]);
h = actxcontrol('mwsamp.mwsampctrl.2',...
[0 0 200 200],f,{'Click','allevents';...
'DblClick','allevents'; 'MouseDown','allevents'})

where allevents.m is:

function allevents(varargin)
if (strcmp(varargin{end-1}.Type, 'Click'))
   disp ('Single Click Event Fired')
elseif (strcmp(varargin{end-1}.Type, 'DblClick'))
   disp ('Double Click Event Fired')
elseif (strcmp(varargin{end-1}.Type, 'MouseDown'))
   disp ('Mousedown Event Fired')
end

Writing Event Handlers as MATLAB Local Functions

Instead of maintaining a separate function file for every event handler routine you write, you can consolidate routines into a single file using local functions.

This example shows three event handler routines, myclick, my2click, and mymoused, implemented as local functions in the file mycallbacks.m. The call to str2func converts the input string to a function handle:

function a = mycallbacks(str) 
a = str2func(str);

function myclick(varargin)
disp('Single click function')

function my2click(varargin)
disp('Double click function')

function mymoused(varargin)
disp('You have reached the mouse down function')
disp('The X position is: ')
double(varargin{5})
disp('The Y position is: ')
double(varargin{6})

To register one of these events, call mycallbacks, passing the name of the event handler:

h = actxcontrol('mwsamp.mwsampctrl.2',[0 0 200 200],gcf,'sampev')
registerevent(h,{'Click',mycallbacks('myclick')})
Was this topic helpful?