Friday, April 14, 2017

Code Snippet: Select feature polygon(s) on Mouse Click ArcObjects C#

Code snippet of custom feature(s) selection tool on mouse click and highlight it using ArcObjects and C#.

 class SelectFeatureTool : ESRI.ArcGIS.Desktop.AddIns.Tool  
   {  
     protected override void OnMouseDown(MouseEventArgs arg)  
     {  
       IMxDocument mxDocument = ArcMap.Application.Document as IMxDocument;  
       IActiveView activeView = mxDocument.ActiveView;  
       IMap map = mxDocument.FocusMap;  
       ILayer layer = map.get_Layer(0); //Get 1st Layer  
       IFeatureLayer featureLayer = (IFeatureLayer) layer;  
   
       IPoint identifyPoint = activeView.ScreenDisplay.DisplayTransformation.ToMapPoint(arg.X, arg.Y);  
       ESRI.ArcGIS.Carto.IIdentify identifyLayer = (IIdentify)layer;  
       IArray array = identifyLayer.Identify(identifyPoint);  
         
       int oid = -1;  
       if (array != null)  
       {  
         object obj = array.get_Element(0);  
         IFeatureIdentifyObj fobj = obj as IFeatureIdentifyObj;  
         IRowIdentifyObject irow = fobj as IRowIdentifyObject;  
         IFeature feature = irow.Row as IFeature;  
         oid = feature.OID;  
       }  
       HighlightClickedFeature(featureLayer, oid, activeView);  
     }  
   
     private void HighlightClickedFeature(IFeatureLayer layer, int featureOid, IActiveView activeView)  
     {  
       IFeatureClass featureClass = layer.FeatureClass;  
       IFeature feature = featureClass.GetFeature(featureOid);  
       IGeometry geometry = feature.Shape;  
   
       ISpatialFilter spatialFilter = new SpatialFilterClass();  
       spatialFilter.Geometry = geometry;  
       spatialFilter.GeometryField = featureClass.ShapeFieldName;  
       spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;  
       spatialFilter.WhereClause = "FID = " + featureOid;  
   
       IFeatureSelection featureSelection = layer as IFeatureSelection;  
         
       if (featureSelection != null)  
       {  
         //featureSelection.SelectFeatures(spatialFilter, esriSelectionResultEnum.esriSelectionResultAdd,false); //multiple selections  
         featureSelection.SelectFeatures(spatialFilter, esriSelectionResultEnum.esriSelectionResultNew, false); //single selection  
         activeView.Refresh();  
       }  
   
       var value = featureSelection.SelectionSet.Count;  
       MessageBox.Show(value.ToString());  
     }  
       
     protected override void OnUpdate()  
     {  
       Enabled = ArcMap.Application != null;  
     }  
       
   }  

.NET , Add-in , ArcMap , arcobject , C#

0 comments :

Post a Comment

 

© 2011 GIS and Remote Sensing Tools, Tips and more .. ToS | Privacy Policy | Sitemap

About Me