ArcObjects Library Reference  

SelectFeatures

About the Custom map selection commands Sample

[C#]

SelectFeatures.cs

using System;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.esriSystem;

namespace SelectCommands
{
	[ClassInterface(ClassInterfaceType.None)]
	[Guid("3362ba66-bf63-442a-a639-d18d583a028d")]
	public sealed class SelectFeatures : BaseTool
	{
        #region COM Registration Function(s)
        [ComRegisterFunction()]
        [ComVisible(false)]
        static void RegisterFunction(Type registerType)
        {
            // Required for ArcGIS Component Category Registrar support
            ArcGISCategoryRegistration(registerType);

            //
            // TODO: Add any COM registration code here
            //
        }

        [ComUnregisterFunction()]
        [ComVisible(false)]
        static void UnregisterFunction(Type registerType)
        {
            // Required for ArcGIS Component Category Registrar support
            ArcGISCategoryUnregistration(registerType);

            //
            // TODO: Add any COM unregistration code here
            //
        }

        #region ArcGIS Component Category Registrar generated code
        /// <summary>
        /// Required method for ArcGIS Component Category registration -
        /// Do not modify the contents of this method with the code editor.
        /// </summary>
        private static void ArcGISCategoryRegistration(Type registerType)
        {
            string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
            ControlsCommands.Register(regKey);

        }
        /// <summary>
        /// Required method for ArcGIS Component Category unregistration -
        /// Do not modify the contents of this method with the code editor.
        /// </summary>
        private static void ArcGISCategoryUnregistration(Type registerType)
        {
            string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
            ControlsCommands.Unregister(regKey);

        }

        #endregion
        #endregion


        private IHookHelper m_hookHelper;
        private System.Windows.Forms.Cursor m_CursorMove;
																	  
		public SelectFeatures()
		{
			//Create an IHookHelper object
            m_hookHelper = new HookHelperClass();

			//Set the tool properties
			base.m_caption = "Select Features";
			base.m_category = "Sample_Select(C#)";
			base.m_name = "Sample_Select(C#)_Select Features";
			base.m_message = "Selects Features By Rectangle Or Single Click";
			base.m_toolTip = "Selects Features";
			base.m_deactivate = true;
			base.m_bitmap = new System.Drawing.Bitmap(GetType().Assembly.GetManifestResourceStream(GetType(), "SelectFeatures.bmp"));
            m_CursorMove = new System.Windows.Forms.Cursor(GetType().Assembly.GetManifestResourceStream(GetType(), "SelectFeatures.cur"));
		}

		public override void OnCreate(object hook)
		{
            m_hookHelper.Hook = hook;
		}
	
		public override bool Enabled
		{
			get
			{
                if (m_hookHelper.FocusMap == null) return false;
                return (m_hookHelper.FocusMap.LayerCount > 0);
			}
		}
	
		public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            IMap map;
            IPoint clickedPoint = m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);

            //If ActiveView is a PageLayout 
            if (m_hookHelper.ActiveView is IPageLayout)
            {
                //See whether the mouse has been clicked over a Map in the PageLayout 
                map = m_hookHelper.ActiveView.HitTestMap(clickedPoint);

                //If mouse click isn't over a Map exit 
                if (map == null)
                    return; 


                //Ensure the Map is the FocusMap 
                if ((!object.ReferenceEquals(map, m_hookHelper.FocusMap)))
                {
                    m_hookHelper.ActiveView.FocusMap = map;
                    m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
                }

                //Still need to convert the clickedPoint into map units using the map's IActiveView 
                clickedPoint = ((IActiveView)map).ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
            }

            else //Or ActiveView is a Map 
            {
                map = m_hookHelper.FocusMap;
            }

            IActiveView activeView = (IActiveView)map;
            IRubberBand rubberEnv = new RubberEnvelopeClass();
            IGeometry geom = rubberEnv.TrackNew(activeView.ScreenDisplay, null);
            IArea area = (IArea)geom;

            //Extra logic to cater for the situation where the user simply clicks a point on the map 
            //or where envelope is so small area is zero 
            if ((geom.IsEmpty == true) || (area.Area == 0))
            {

                //create a new envelope 
                IEnvelope tempEnv = new EnvelopeClass();

                //create a small rectangle 
                ESRI.ArcGIS.esriSystem.tagRECT RECT = new tagRECT();
                RECT.bottom = 0;
                RECT.left = 0;
                RECT.right = 5;
                RECT.top = 5;

                //transform rectangle into map units and apply to the tempEnv envelope 
                IDisplayTransformation dispTrans = activeView.ScreenDisplay.DisplayTransformation;
                dispTrans.TransformRect(tempEnv,ref RECT, 4); //4 = esriDisplayTransformationEnum.esriTransformToMap)
                tempEnv.CenterAt(clickedPoint);
                geom = (IGeometry)tempEnv;
            }

            //Set the spatial reference of the search geometry to that of the Map 
            ISpatialReference spatialReference = map.SpatialReference;
            geom.SpatialReference = spatialReference;

            map.SelectByShape(geom, null, false);
            activeView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, activeView.Extent);
        } 
	
		public override int Cursor
		{
			get
			{
				return m_CursorMove.Handle.ToInt32();
				
			}
		}
	}
}

[Visual Basic .NET]

SelectFeatures.vb

Option Explicit On 

Imports ESRI.ArcGIS.Carto
Imports ESRI.ArcGIS.Display
Imports ESRI.ArcGIS.Geometry
Imports ESRI.ArcGIS.Controls
Imports ESRI.ArcGIS.ADF.BaseClasses
Imports ESRI.ArcGIS.ADF.CATIDs
Imports System.Runtime.InteropServices
Imports ESRI.ArcGIS.esriSystem

<ComClass(SelectFeatures.ClassId, SelectFeatures.InterfaceId, SelectFeatures.EventsId)> _
Public NotInheritable Class SelectFeatures

    Inherits BaseTool

    Private m_pHookHelper As IHookHelper
    Private m_pCursorMove As System.Windows.Forms.Cursor

#Region "COM GUIDs"
    'These GUIDs provide the COM identity for this class and its COM interfaces. 
    'If you change them, existing clients will no longer be able to access the class.
    Public Const ClassId As String = "310bd6df-9422-44c0-9158-f8e63aa4254e"
    Public Const InterfaceId As String = "8cca1681-2c5c-4c06-9760-fd9f3ca70908"
    Public Const EventsId As String = "ab0d2a64-3473-477b-a28d-93dc5e3820cc"
#End Region
#Region "COM Registration Function(s)"
    <ComRegisterFunction(), ComVisibleAttribute(False)> _
    Public Shared Sub RegisterFunction(ByVal registerType As Type)
        ' Required for ArcGIS Component Category Registrar support
        ArcGISCategoryRegistration(registerType)

        'Add any COM registration code after the ArcGISCategoryRegistration() call

    End Sub

    <ComUnregisterFunction(), ComVisibleAttribute(False)> _
    Public Shared Sub UnregisterFunction(ByVal registerType As Type)
        ' Required for ArcGIS Component Category Registrar support
        ArcGISCategoryUnregistration(registerType)

        'Add any COM unregistration code after the ArcGISCategoryUnregistration() call

    End Sub

#Region "ArcGIS Component Category Registrar generated code"
    ''' <summary>
    ''' Required method for ArcGIS Component Category registration -
    ''' Do not modify the contents of this method with the code editor.
    ''' </summary>
    Private Shared Sub ArcGISCategoryRegistration(ByVal registerType As Type)
        Dim regKey As String = String.Format("HKEY_CLASSES_ROOT\CLSID\{{{0}}}", registerType.GUID)
        ControlsCommands.Register(regKey)

    End Sub
    ''' <summary>
    ''' Required method for ArcGIS Component Category unregistration -
    ''' Do not modify the contents of this method with the code editor.
    ''' </summary>
    Private Shared Sub ArcGISCategoryUnregistration(ByVal registerType As Type)
        Dim regKey As String = String.Format("HKEY_CLASSES_ROOT\CLSID\{{{0}}}", registerType.GUID)
        ControlsCommands.Unregister(regKey)

    End Sub

#End Region
#End Region

    Public Sub New()
        MyBase.New()

        'Create an IHookHelper object
        m_pHookHelper = New HookHelperClass

        'Set the tool properties
        MyBase.m_caption = "Select Features"
        MyBase.m_category = "Sample_Select(VB.NET)"
        MyBase.m_name = "Sample_Select(VB.NET)_Select Features"
        MyBase.m_message = "Selects Features By Rectangle Or Single Click"
        MyBase.m_toolTip = "Selects Features"
        MyBase.m_deactivate = True
        MyBase.m_bitmap = New System.Drawing.Bitmap(GetType(SelectFeatures).Assembly.GetManifestResourceStream(GetType(SelectFeatures), "SelectFeatures.bmp"))
        m_pCursorMove = New System.Windows.Forms.Cursor(GetType(SelectFeatures).Assembly.GetManifestResourceStream(GetType(SelectFeatures), "SelectFeatures.cur"))
    End Sub

    Public Overrides Sub OnCreate(ByVal hook As Object)
        m_pHookHelper.Hook = hook
    End Sub

    Public Overrides ReadOnly Property Enabled() As Boolean
        Get
            If (m_pHookHelper.FocusMap Is Nothing) Then Exit Property
            Return (m_pHookHelper.FocusMap.LayerCount > 0)
        End Get
    End Property

    Public Overrides Sub OnMouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Integer, ByVal Y As Integer)

        Dim map As IMap
        Dim clickedPoint As IPoint = m_pHookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y)

        'If ActiveView is a PageLayout
        If TypeOf m_pHookHelper.ActiveView Is IPageLayout Then

            'See whether the mouse has been clicked over a Map in the PageLayout
            map = m_pHookHelper.ActiveView.HitTestMap(clickedPoint)

            'If mouse click isn't over a Map exit
            If map Is Nothing Then Exit Sub

            'Ensure the Map is the FocusMap
            If Not map Is m_pHookHelper.FocusMap Then
                m_pHookHelper.ActiveView.FocusMap = map
            End If

            'Still need to convert the clickedPoint into map units using the map's IActiveView 
            clickedPoint = CType(map, IActiveView).ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y)

        Else 'Or ActiveView is a Map
            map = m_pHookHelper.FocusMap
        End If

        Dim activeView As IActiveView = CType(map, IActiveView)
        Dim rubberEnv As IRubberBand = New RubberEnvelopeClass()
        Dim geom As IGeometry = rubberEnv.TrackNew(activeView.ScreenDisplay, Nothing)
        Dim area As IArea = CType(geom, IArea)

        'Extra logic to cater for the situation where the user simply clicks a point on the map
        'or where envelope is so small area is zero
        If (geom.IsEmpty = True) OrElse (area.Area = 0) Then

            'create a new envelope
            Dim tempEnv As IEnvelope = New EnvelopeClass()

            'create a small rectangle
            Dim RECT As ESRI.ArcGIS.esriSystem.tagRECT = New tagRECT()
            RECT.bottom = 0
            RECT.left = 0
            RECT.right = 5
            RECT.top = 5

            'transform rectangle into map units and apply to the tempEnv envelope
            Dim dispTrans As IDisplayTransformation = activeView.ScreenDisplay.DisplayTransformation
            dispTrans.TransformRect(tempEnv, RECT, 4) 'esriDisplayTransformationEnum.esriTransformToMap);
            tempEnv.CenterAt(clickedPoint)
            geom = CType(tempEnv, IGeometry)
        End If

        'Set the spatial reference of the search geometry to that of the Map
        Dim spatialReference As ISpatialReference = map.SpatialReference
        geom.SpatialReference = spatialReference

        map.SelectByShape(geom, Nothing, False)
        activeView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, Nothing, activeView.Extent)

    End Sub

    Public Overrides ReadOnly Property Cursor() As Integer
        Get
            Return m_pCursorMove.Handle.ToInt32
        End Get
    End Property

End Class