Wednesday, August 31, 2011

Enabling a Short Cut Key on a Certain Context in your UI

Requirement :
Ctrl + F is already used for Find in most of the Views and Editors in Eclipse.
Ctrl + F in my View should display a Message BOX.

Solution : Create a Context where Ctrl + F will display a Message Box.
-------------------------------------------
Enabling a Short Cut Key on a Certain Context in your UI

1.Create the Command using Extension Point : org.eclipse.ui.commands.
Fill id, name. Leave the Default Handler blank.
2.Add an Extension for Extension Point : org.eclipse.ui.contexts
Fill id, name and assign parentId : org.eclipse.ui.contexts.window.
3.Create a Key Binding using Extension Point : org.eclipse.ui.bindings
Fill the Sequence, schemeId : as defaulAcceleratorConfiguration, contextId : as in step 2, commandId: as in Step3
-------------------------------------------
Now associating the created Context to a Context in your Workbench.
Open the View/Editor where you want Ctrl + F to display a Message BOX.

in CreatePartControl method
we need to call a private method activateHandlers();
In activateHandlers method
1. We need to register and activate the Context that we created in Step 2 above.
2. We also need to create an Handler to display a Message Box.
3. Associate the handler with the Command that we created in Step 1 above.

This will associate enable Ctrl + F to work differently on your View/Editor.
-------------------------------------------
Because you created the Context and the Handler, you are responsible to dispose away the same.


Code Snippet ::

For Dispose Method :: override the one in View/Editor
@Override
public void dispose() {
if(fAddHandler != null) {
fAddHandler.dispose();
}
}

For activateHandlers()
private void activateHandlers() {
ICommandService commandSupport = (ICommandService)getSite().getService(ICommandService.class);
IHandlerService handlerService = (IHandlerService)getSite().getService(IHandlerService.class);
contextService = (IContextService)getSite().getService(IContextService.class);

if (commandSupport != null && handlerService != null && contextService != null)
{
activation = contextService.activateContext("org.ancit.examples.commands.samplecontext");

fAddHandler = new AbstractHandler() {
public Object execute(ExecutionEvent event) throws ExecutionException {

action1.run();
return null;
}};
handlerService.activateHandler("org.ancit.examples.commands.commands.sampleCommand", fAddHandler);
}

}


0 comments: