How do I know about execution of a command?
You can use the IExecutionListener:
ICommandService service = (ICommandService) serviceLocator.getService(ICommandService.class);
service.addExecutionListener(new IExecutionListener() {public void notHandled(String commandId, NotHandledException exception) {
}public void postExecuteFailure(String commandId, ExecutionException exception) {
}public void postExecuteSuccess(String commandId, Object returnValue) {
}public void preExecute(String commandId, ExecutionEvent event) {
}
});
The IExecutionListener is merely an observer of the command execution so it can neither veto on it nor make any changes to the event.
How do I get the active Window/Shell in my handler code?
Use HandlerUtil. Its a handy class which gives you access to most common variables like active window, active shell, context ids, active part, current selection, etc.
Shell shell = HandlerUtil.getActiveShell(event);
ISelection selection = HandlerUtil.getCurrentSelection(event);
All of the get* methods will have a get*Checked variants. The first ones will return you null if the variable is not available. The checked ones will throw you an exception if the variable is null. If you have your own variable, you can use the getVariable() method to get it.
Can I programmatically execute a Command?
Yes. But don't simple call command.execute(), use the IHandlerService to execute a command:
IHandlerService handlerService = (IHandlerService) serviceLocator.getService(IHandlerService.class);
handlerService.executeCommand(commandId, null);
Can I programmatically create and manipulate a Command?
Yes! You can use ICommandService to create a new command and then associate a handler thru IHandlerService:
ICommandService commandService = (ICommandService) serviceLocator.getService(ICommandService.class);
Command command = commandService.getCommand("my.new.undefined.command");
command.define("New Command", "This is created Programatically!",
commandService.getCategory("org.eclipse.ui.category.window"));IHandlerService handlerService = (IHandlerService) serviceLocator.getService(IHandlerService.class);
handlerService.activateHandler(command.getId(), new AbstractHandler() {public Object execute(ExecutionEvent event) throws ExecutionException {
System.out.println("Command executed !");
return null;
}
});
See also:
Part 1: Actions Vs Commands
Part 2: Selection and Enablement of Handlers
Part 3: Parameters for Commands
Part 5: ISourceProvider & dynamically updating Commands
Part 6: 'toggle' & 'radio' style menu contribution
11 comments: