1. 程式人生 > >rcp(外掛開發)Command 傳值的問題

rcp(外掛開發)Command 傳值的問題

有這樣一個需求:如果想在command執行的時候攜帶一些資訊,然後還想獲取這些資訊 這個如何實現呢?

一 傳值部分(傳遞的是ExecutionEvent,通過ExecutionEvent攜帶的ApplicationContext傳遞物件,還可以傳遞別的型別如MAP)

//獲取ICommandService

ICommandService commandService = (ICommandService) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart().getSite().getService(ICommandService.class);

//呼叫Command並傳遞物件

commandService.getCommand("CommandId").executeWithChecks(new ExecutionEvent(null, Collections.EMPTY_MAP, null, sendObject));

二 取值部分 這個是在command相關聯的handler裡取到這個ExecutionEvent,ExecutionEvent裡攜帶相關傳入的資訊。

package command_test.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.jface.dialogs.MessageDialog;

/**
 * Our sample handler extends AbstractHandler, an IHandler base class.
 * @see org.eclipse.core.commands.IHandler
 * @see org.eclipse.core.commands.AbstractHandler
 */
public class SampleHandler extends AbstractHandler {
 /**
  * The constructor.
  */
 public SampleHandler() {
 }

 /**
  * the command has been executed, so extract extract the needed information
  * from the application context.
  */
 public Object execute(ExecutionEvent event) throws ExecutionException {
  IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
  MessageDialog.openInformation(
    window.getShell(),
    "Command_Test",
    "Hello, Eclipse world");
  return null;
 }
}