Navigation:  Application Architecture > Putting it All Together > Designing a Tool >

Fleshing out the logic

Previous pageReturn to chapter overviewNext page

Having added the attributes, we can expect that a Tools > Text Editor menu item will appear on the main menu, and that when a user clicks on this item our Launch method will be invoked.  We must implement the Launch method to launch the text editor in the desktop.

We have several choices here: the text editor could appear in a shelf, in a modal dialog, or in a workspace.  We simply need to decide which type of host we would like to use, and call the corresponding static convenience method on the ApplicationComponent class.

Let’s decide that we would like it to appear in a workspace, in which case we can implement the launch method as:

 

public void Launch()

{

   _component = new TextEditorComponent();

   _workspace = ApplicationComponent.LaunchAsWorkspace(

      this.Context.DesktopWindow,

      _component,

      "Text Editor");

 

   _workspace.Closed += Workspace_Closed;

}

 

Let’s examine each argument passed to ApplicationComponent.LaunchAsWorkspace:

The first argument, this.Context.DesktopWindow, is a reference to the IDesktopWindow in which the workspace should be created.  When we derived our tool from the DesktopTool base class, we inherited a Context property that returns an IDesktopToolContext, which we then use to obtain the desktop window in which our tool is operating.

The second argument, _component, is simply the component (instantiated in the line above) to be hosted in the workspace.

The third argument provides a title for the workspace that will host our component.

Notice that we also subscribe to the workspace's Closed event, since we may want to perform some action when the workspace (and thus the component) is closed.  The rest of the code looks like this:

 

protected override void Dispose(bool disposing)

{

   if (_workspace != null)

      _workspace.Closed -= Workspace_Closed;

 

   base.Dispose(disposing);

}

 

private void Workspace_Closed(object sender, ClosedEventArgs e)

{

   // Check the exit code if necessary

   if (_component.ExitCode == ApplicationComponentExitCode.Accepted)

   {

      // Do something

   }

}

 

There a couple of things worth noting here:

1.If we want, we can check the exit code of the component to determine how the component exited, (e.g., accepted, cancelled, etc.)
2.The disposal pattern here is important: If the Closed event is subscribed to, you must unsubscribe in the Dispose method, since if the workspace and component for some reason outlives the tool itself, the event will fire but an invalid event handler will be called, resulting in an unhandled exception.