C#-Beispielprojekt

www.altova.com Dieses Kapitel drucken Vorherige Seite Eine Ebene nach oben Nächste Seite

Startseite >  Die MapForce API > Übersicht > Beispiele >

C#-Beispielprojekt

Nach Installation von MapForce steht ein MapForce API Client-Projekt für C# im folgenden Verzeichnis zur Verfügung: C:/Benutzer/<Benutzername>/Dokumente/Altova/MapForce2019/MapForceExamples/API.

 

 

Sie können das Projekt mit Visual Studio 2008 oder höher kompilieren. Führen Sie dazu das Beispiel aus, öffnen Sie die Projektmappendatei (.sln) in Visual Studio und führen Sie den Befehl Debugging | Debugging starten oder Debugging | Starten ohne Debugging aus.

 

Anmerkung:Wenn Sie ein 64-Bit-Betriebssystem haben und eine 32-Bit-Version von MapForce verwenden, fügen Sie die x86-Plattform im Konfigurations-Manager der Projektmappe hinzu und erstellen Sie das Beispiel mittels "Build" mit dieser Konfiguration. Im Dialogfeld "Neue Projektmappenplattform" (Build | Konfigurations-Manager | Aktive Projektmappenplattform | <Neu…>) kann eine neue x86-Plattform (für die aktive Projektmappen in Visual Studio) erstellt werden.

 

Wenn Sie das Beispiel ausführen, wird ein Windows-Formular mit Schaltflächen zum Aufrufen der grundlegenden MapForce-Operationen angezeigt:

 

Starten von MapForce
Erstellen eines neuen Mapping-Designs
Öffnen der Datei CompletePO.mfd aus dem Ordner ...\MapForceExamples (möglicherweise müssen Sie den Pfad für den Ordner \MapForceExamples auf Ihrem Rechner anpassen)
Generieren von C#-Code in einem Temp-Verzeichnis
Beenden von MapForce

 

mfapi_cs_sample

 

Codefragment

Das Codefragment enthält zum besseren Verständnis Kommentare. Vom Aufbau her besteht der Code aus einer Reihe von Handlern für die Schaltflächen auf der oben gezeigten Benutzeroberfläche.

 

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);
          }
      }
  }
}


© 2019 Altova GmbH