Altova MapForce 2024 Professional Edition

Una vez haya instalado MapForce podrá encontrar un ejemplo de proyecto cliente de la API de MapForce en C# en el directorio C:/Users/<username>/Documents/Altova/MapForce2024/MapForceExamples/API.

 

Puede compilar y ejecutar el proyecto con Visual Studio 2008 o superior. Para compilar y ejecutar el ejemplo, abra el archivo de la solución .sln en Visual Studio y ejecute Depurar | Iniciar depuración o Depurar | Iniciar sin depurar.

 

Nota:Si tiene un sistema operativo de 64 bits y está usando una versión de MapForce de 32 bits, añada la plataforma x86 al Administrador de configuración de la solución y compile el ejemplo usando esta configuración. Se puede crear una nueva plataforma x86 (para la solución activa de Visual Studio) en el cuadro de diálogo Nueva plataforma de solución (Compilar | Administrador de configuración | Plataforma de soluciones activas | <Nueva...>)

 

Cuando ejecute el ejemplo se mostrará un cuadro de diálogo de Windows que contiene botones que invocan operaciones básicas de MapForce:

 

Start MapForce (iniciar MapForce)

Create a new mapping design (Crear un nuevo diseño de asignación)

Open the CompletePO.mfd (abrir el archivo CompletePO.mfd de la carpeta ...\MapForceExamples). Recuerde que puede que tenga que ajustar la ruta para que apunte a la carpeta \MapForceExamples en su equipo.

Generate C# code in a temp directory (Generar código C# en un directorio temporal)

Shut down MapForce (cerrar MapForce)

mfapi_cs_sample

 

Fragmento de código

El fragmento contiene comentarios para facilitar su comprensión. El código consiste básicamente en una serie de controladores para los botones de la interfaz de usuario que se muestra más arriba.

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace WindowsFormsApplication2
{
  public partial class Form1 : Form
  {
      public Form1()
      {
          InitializeComponent();
      }
 
      // An instance of MapForce accessed via its automation interface.
      MapForceLib.Application MapForce;
 
      // Location of examples installed with MapForce
      String strExamplesFolder;
 
      private void Form1_Load(object sender, EventArgs e)
      {
      }
 
      // handler for the "Start MapForce" button
      private void StartMapForce_Click(object sender, EventArgs e)
      {
          if (MapForce == null)
          {
              Cursor.Current = Cursors.WaitCursor;
 
              // if we have no MapForce instance, we create one a nd make it visible.
              MapForce = new MapForceLib.Application();
              MapForce.Visible = true;
 
              // locate examples installed with MapForce.
              int majorVersionYear = MapForce.MajorVersion + 1998;
              strExamplesFolder = Environment.GetEnvironmentVariable("USERPROFILE") + "\\My Documents\\Altova\\MapForce" + Convert.ToString(majorVersionYear) + "\\MapForceExamples\\";
 
              Cursor.Current = Cursors.Default;
          }
          else
          {
              // if we have already an MapForce instance running we toggle its visibility flag.
              MapForce.Visible = !MapForce.Visible;
          }
      }
 
      // handler for the "Open CompletePO.mfd" button
      private void openCompletePO_Click(object sender, EventArgs e)
      {
          if (MapForce == null)
              StartMapForce_Click(null, null);
 
          // Open one of the sample files installed with the product.
          MapForce.OpenDocument(strExamplesFolder + "CompletePO.mfd");
      }
 
      // handler for the "Create new mapping" button
      private void newMapping_Click(object sender, EventArgs e)
      {
          if (MapForce == null)
              StartMapForce_Click(null, null);
 
          // Create a new mapping
          MapForce.NewMapping();
      }
 
      // handler for the "Shutdown MapForce" button
      // shut-down application instance by explicitly releasing the COM object.
      private void shutdownMapForce_Click(object sender, EventArgs e)
      {
          if (MapForce != null)
          {
              // allow shut-down of MapForce by releasing UI
              MapForce.Visible = false;
 
              // explicitly release COM object
              try
              {
                  while (System.Runtime.InteropServices.Marshal.ReleaseComObject(MapForce) > 0) ;
              }
              finally
              {
                  // avoid later access to this object.
                  MapForce = null;
              }
          }
      }
 
      // handler for button "Generate C# Code"
      private void generateCppCode_Click(object sender, EventArgs e)
      {
          if (MapForce == null)
              listBoxMessages.Items.Add("start MapForce first.");
          // COM errors get returned to C# as exceptions. We use a try/catch block to handle them.
          try
          {
              MapForceLib.Document doc = MapForce.ActiveDocument;
 
              listBoxMessages.Items.Add("Active document " + doc.Name);
              doc.GenerateCHashCode();
 
          }
          catch (Exception ex)
          {
              // The COM call was not successful.
              // Probably no application instance has been started or no document is open.
              MessageBox.Show("COM error: " + ex.Message);
          }
      }
 
      delegate void addListBoxItem_delegate(string sText);
      // called from the UI thread
      private void addListBoxItem(string sText)
      {
          listBoxMessages.Items.Add(sText);
      }
      // wrapper method to allow to call UI controls methods from a worker thread
      void syncWithUIthread(Control ctrl, addListBoxItem_delegate methodToInvoke, String sText)
      {
          // Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing.
          // Control.BeginInvoke: Executes on the UI thread, and calling thread doesn't wait for completion.
          if (ctrl.InvokeRequired)
              ctrl.BeginInvoke(methodToInvoke, new Object[] { sText });
      }
 
      // event handler for OnDocumentOpened event
      private void handleOnDocumentOpened(MapForceLib.Document i_ipDocument)
      {
          String sText = "";
 
          if (i_ipDocument.Name.Length > 0)
              sText = "Document " + i_ipDocument.Name + " was opened!";
          else
              sText = "A new mapping was created.";
 
          // we need to synchronize the calling thread with the UI thread because
          // the COM events are triggered from a working thread
          addListBoxItem_delegate methodToInvoke = new addListBoxItem_delegate(addListBoxItem);
          // call syncWithUIthread with the following arguments:
          // 1 - listBoxMessages - list box control to display messages from COM events
          // 2 - methodToInvoke  - a C# delegate which points to the method which will be called from the UI thread
          // 3 - sText           - the text to be displayed in the list box
          syncWithUIthread(listBoxMessages, methodToInvoke, sText);
      }
       
      private void checkBoxEventOnOff_CheckedChanged(object sender, EventArgs e)
      {
          if (MapForce != null)
          {
              if (checkBoxEventOnOff.Checked)
                  MapForce.OnDocumentOpened += new MapForceLib._IApplicationEvents_OnDocumentOpenedEventHandler(handleOnDocumentOpened);
              else
                  MapForce.OnDocumentOpened -= new MapForceLib._IApplicationEvents_OnDocumentOpenedEventHandler(handleOnDocumentOpened);
          }
      }
  }
}

© 2018-2024 Altova GmbH