ArcGIS Engine开发Geodatabase代码(六)——TopologyEdit

/******************************************/
 * ESRI Developer Summit 2009
 * Developer's Guide to the Geodatabase
 * Code Samples
 * 6 April 2009
/******************************************/
偶然间整理电脑的文件夹,发现在Esri官网上曾经下载过关于Geodatabase开发的相关代码示例,赶紧跟各位共享一下
开发环境:
  • ArcGIS Engine9.3/9.3.1
  • VS2008
说明:该代码适用于ArcGIS Engine初学者,或者对Geodatabase开发感兴趣的朋友,如果你的Engine版本高于9.3.1,可能相关的接口会发生变化,这个需要用户自己来进行修改,但是聪明的用户不会局限于代码的是否允许,也许学习一下人家的接口使用方法,开发模式才是最重要的。

关于版本的接口差别参考:http://help.arcgis.com/en/sdk/10.0/arcobjects_net/conceptualhelp/index.html#/Type_changes_between_9_3_and_10/000100000408000000/


以下代码主要是对拓扑编辑做相关介绍
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Editor;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Framework;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;

namespace TopologyEditDemo
{
  [Guid("35d59a9d-997c-4536-a003-3c6ed77abb92")]
  [ClassInterface(ClassInterfaceType.None)]
  [ProgId("TopologyEditDemo.TopologyEditCommand")]
  public sealed class TopologyEditCommand : BaseCommand
  {
    #region COM Registration Function(s)
    [ComRegisterFunction()]
    [ComVisible(false)]
    static void RegisterFunction(Type registerType)
    {
			String regKey = String.Format(@"HKEY_CLASSES_ROOT\CLSID\{{{0}}}", registerType.GUID);
			MxCommands.Register(regKey);
    }

    [ComUnregisterFunction()]
    [ComVisible(false)]
    static void UnregisterFunction(Type registerType)
    {
			String regKey = String.Format(@"HKEY_CLASSES_ROOT\CLSID\{{{0}}}", registerType.GUID);
			MxCommands.Unregister(regKey);
    }
    #endregion

		#region Instance Variables
		/// <summary>
		/// A helper for working with ArcMap.
		/// </summary>
		private IHookHelper hookHelper = null;

		/// <summary>
		/// A reference to the application (ArcMap).
		/// </summary>
		private IApplication application = null;
		#endregion

		#region Constructors
		/// <summary>
		/// The default constructor.
		/// </summary>
		public TopologyEditCommand()
    {
			// Set the command's properties.
      m_category = "2009 DevSummit";
			m_caption = "TopologyEditCommand";
      m_message = "Editing using the Topology Graph";
			m_toolTip = "TopologyEditCommand";
			m_name = String.Format("{0}_{1}", m_category, m_caption);

			// Set the command's image.
      try
      {
        String bitmapResourceName = "TopologyEditCommand.bmp";
        m_bitmap = new Bitmap(GetType(), bitmapResourceName);
      }
      catch (Exception exc)
      {
        Trace.WriteLine(exc.Message, "Invalid Bitmap");
      }
		}
		#endregion

		#region Overridden Class Methods
		/// <summary>
		/// Occurs when the command is created.
		/// </summary>
		/// <param name="hook">A reference to the application.</param>
		public override void OnCreate(object hook)
    {
      // Setup the HookHelper and get a reference to application.
			hookHelper = new HookHelperClass { Hook = hook };
      application = (IApplication)hook;
    }

    /// <summary>
    /// Indicates whether the command is enabled. True if features are selected.
    /// </summary>
    public override Boolean Enabled
    {
      get
      {
        IMap map = hookHelper.FocusMap;
        IEnumFeature enumFeature = (IEnumFeature)map.FeatureSelection;
				return enumFeature.Next() != null;
      }
    }

		/// <summary>
		/// Occurs when the command is clicked.
		/// </summary>
		public override void OnClick()
    {
      try
      {
				// Get a reference to the focus map, the active view, and the Editor.
        IMap map = hookHelper.FocusMap;
				IActiveView activeView = hookHelper.ActiveView;
        IEditor editor = (IEditor)application.FindExtensionByName("ESRI Object Editor");

				// Get the first selected feature.
        IEnumFeature enumFeature = (IEnumFeature)map.FeatureSelection;
        IEnumFeatureSetup enumFeatureSetup = (IEnumFeatureSetup)enumFeature;
        enumFeatureSetup.AllFields = true;
        IFeature feature = enumFeature.Next();

				// Request a move distance from the user.
        Double yMoveDistance = Double.Parse(InputBox.ShowInputBox());

        // Assume that there is a Topology layer in position 0 in the TOC.
				ITopologyLayer topologyLayer = map.get_Layer(0) as ITopologyLayer;
        if (topologyLayer != null)
        {
					// Open the topology graph.
          ITopology topology = topologyLayer.Topology;          
          ITopologyGraph topologyGraph = topology.Cache;

          // Check to see if an existing graph is built for the area of interest.
          IEnvelope existingGraphEnv = topologyGraph.BuildExtent;
					IEnvelope activeViewEnv = activeView.Extent;
          if (!existingGraphEnv.IsEmpty)
          {
						IClone graphEnvClone = (IClone)existingGraphEnv;
						IClone activeViewExtentClone = (IClone)activeViewEnv;
						if (!graphEnvClone.IsEqual(activeViewExtentClone))
            {
              // We could build the cache using the Geodatasets extent but 
              // Cook County is large. This demo uses the ArcMap extent, 
              // but any envelope could be passed in.
							topologyGraph.Build(activeViewEnv, false);
            }
          }
          else
          {
						topologyGraph.Build(activeViewEnv, false);
          }

					// Copy the first selected feature's geometry and use it to
					// make a selection in the topology graph.
          IGeometry geometry = feature.ShapeCopy;
          topologyGraph.SelectByGeometry(
              (int)esriTopologyElementType.esriTopologyNode,
               esriTopologySelectionResultEnum.esriTopologySelectionResultNew,
               geometry);

					// Create a transformation.
          IAffineTransformation2D affine = new AffineTransformation2DClass();
          affine.Move(0, yMoveDistance);

          // Start editing.
          IDataset dataset = (IDataset)topology.FeatureDataset;
          editor.StartEditing(dataset.Workspace);
          editor.StartOperation();

          topologyGraph.TransformSelection(esriTransformDirection.esriTransformForward, affine, false);

          // Commit the topology edit in the database.
          // The post will tell you the envelope of the area which has changed.
					IEnvelope invalidArea = null;
          topologyGraph.Post(out invalidArea);

          editor.StopOperation("Stop operation");
          editor.StopEditing(true);

          activeView.Refresh();
        }
        else
        {
          MessageBox.Show("Topology is not the first layer in TOC", "TopologyGraphEditCommand");
          return;
        }
      }
      catch (COMException comExc)
      {
        MessageBox.Show(String.Format("Error ({0}): {1}", comExc.ErrorCode, comExc.Message));
      }
      catch (Exception exc)
      {
        MessageBox.Show(String.Format("Error: {0}", exc.Message));
      }
    }
    #endregion

    #region Inputbox Class
		/// <summary>
		/// A form for inputting a simple numeric value. 
		/// </summary>
    public class InputBox : Form
		{
			#region Instance Variables
			/// <summary>
			/// The form's text box.
			/// </summary>
			private TextBox textBox = null;
			#endregion

			#region Constructors and Initialization
			/// <summary>
			/// The default constructor.
			/// </summary>
			private InputBox()
      {
        InitializeComponent();
			}

			/// <summary>
			/// Initializes the form and its components.
			/// </summary>
			private void InitializeComponent()
			{
				// Create the text box.
				textBox = new TextBox()
				{
					Location = new System.Drawing.Point(16, 16),
					Name = "TextBox",
					Size = new Size(256, 20),
					TabIndex = 0,
					Text = "30"
				};
				textBox.KeyDown += new KeyEventHandler(OnKeyDown);

				SuspendLayout();

				// Set this object's inherited properties.
				AutoScaleBaseSize = new Size(5, 13);
				ClientSize = new Size(292, 53);
				ControlBox = false;
				Controls.AddRange(new Control[] { textBox });
				FormBorderStyle = FormBorderStyle.FixedDialog;
				Name = "InputBox";
				Text = "Enter 2D Transform Vertical Distance";

				ResumeLayout(false);
			}
			#endregion

			#region Public Methods
			/// <summary>
			/// Gets the value entered in the text box.
			/// </summary>
			public String Value
			{
				get { return textBox.Text; }
			}
			#endregion

			#region Event Handlers
			/// <summary>
			/// Occurs when a key is pressed in the text box.
			/// </summary>
			/// <param name="sender">The source of the event.</param>
			/// <param name="e">Event arguments.</param>
			private void OnKeyDown(object sender, KeyEventArgs e)
      {
        if (e.KeyCode == Keys.Enter)
          this.Close();
			}
			#endregion

			#region Static Methods
			/// <summary>
			/// Displays a new instance of the InputBox and returns the value entered.
			/// </summary>
			/// <returns>The value entered by the user.</returns>
			public static String ShowInputBox()
      {
        InputBox box = new InputBox();
        box.ShowDialog();
        return box.Value;
			}
			#endregion
		}
    #endregion
  }
}

你可能感兴趣的:(ArcGIS Engine开发Geodatabase代码(六)——TopologyEdit)