【030】◀▶ ArcEngine 一些實現代碼


---------------------------------------------------------------------------------------------------------

●·● 目錄:

A1 ………… 實現:鼠標滑過顯示要素 tip
A2 ………… 實現:通過鼠標選擇要素並高亮顯示(ISelectionEnvironment
A3 ………… 實現:只顯示篩選的要素(IFeatureLayerDefinition
A4 ………… 實現:高亮顯示篩選的要素(IFeatureSelection
A5 ………… 實現:類似 ArcMap 中 Identify 工具的效果(IIdentify、IArray、IIdentifyObj
A6 ………… 實現:在 MapControl 上繪制幾何圖形
          實現:在 MapControl 上繪制幾何圖形(IGraphicsContainer,幾何:圓)

A7 ………… 實現:在 MapControl 自由旋轉地圖(IScreenDisplay [RotateMoveTo])
                   實現:在 MapControl 中鼠標與地圖反向移動(IScreenDisplay [PanMoveTo])

A8 ………… 實現:彈出顏色選擇器(IColorPalette、IColorSelector、IColorBrowser
          實現:獲取控件的屏幕位置(兩種方法)

A9 ………… 實現:Symbol 對象(ISimpleMarkerSymbol、Arrow、Character、Picture)

 

G1 ………… 實現:Symbol 對象
G2 ………… 實現:顯示圖層的屬性窗口
G3 ………… 實現:PageLayoutControl 的樣式設置(IBorder、IBackground、IShadow、IMapGrid
G4 ………… 實現:刪除shapefile文件中的重復數據
G5 ………… 實現:MapControl 與 PageLayoutControl 的交互
G6 ………… 實現:制作可以浮動的工具欄
G7 ………… 實現:ArcGIS Engine 實現鷹眼 & 分析(IGraphicsContainer、IFillShapeElement
G8 ………… 實現:獨立窗口的鷹眼顯示(IHookHelper
G9 ………… 實現:自定義工具窗口(ICustomizeDialog、ICustomizeDialogEvents

 

U1 ………… 實現:Map 與 PageLayout 切換后工具不變
U2 ………… 實現:在窗體中顯示漸變顏色 & 根據名稱獲取控件(IAlgorithmicColorRamp、IEnumColor
U3 ………… 實現:獲取地圖是否處於編輯狀態(IDataset、IWorkspaceEdit
U4 ………… 實現:為某一要素添加字段內容(IFeature
U5 ………… 實現:獲取地圖是否處於編輯狀態
U6 ………… 實現:獲取地圖是否處於編輯狀態

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A1個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:鼠標滑過顯示要素 tip

對於這個有兩個方法:

第一種:通過將 axmapcontrol 自帶的 ShowMapTips 屬性設置為 true 來實現。

第二種:通過 .NET 自帶的控件 ToolTip 來實現!

第一種代碼:

private void axMapControl1_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
{
axMapControl1.ShowMapTips = true;
IFeatureLayer pFeatureLayer = axMapControl1.Map.get_Layer(0) as IFeatureLayer;
pFeatureLayer.DisplayField = "Name";
pFeatureLayer.ShowTips = true;
}

第二種代碼:

private void axMapControl1_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
{
IFeatureLayer pFeatureLayer = axMapControl1.Map.get_Layer(0) as IFeatureLayer;
pFeatureLayer.DisplayField = "Name";
pFeatureLayer.ShowTips = true;
string pTip;
pTip = pFeatureLayer.get_TipText(e.mapX, e.mapY, axMapControl1.ActiveView.FullExtent.Width / 10000);
if (pTip != null)
{
toolTip1.SetToolTip(axMapControl1, "名稱:" + pTip);
}
else //當 ToolTip 空間顯示的內容為 null 的時候,就不會顯示了!相當於隱藏了!
{
toolTip1.SetToolTip(axMapControl1, "");
}
}

以上兩種方法都可以實現顯示標注,但是第二種效果更好一點~!

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A2個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:通過鼠標選擇要素並高亮顯示

---------------------------------------------------------------------------------------------------------

●·● ISelectionEnvironment 接口

---------------------------------------------------------------------------------------------------------

通過 IMap 接口的 SelectByShape 方法來實現!同時可以修改高亮顯示的顏色!

        private void axMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
{
axMapControl1.MousePointer = esriControlsMousePointer.esriPointerDefault;
IMap pMap = axMapControl1.Map;
IGeometry pGeometry = axMapControl1.TrackRectangle(); //獲取框選幾何
ISelectionEnvironment pSelectionEnv = new SelectionEnvironment(); //新建選擇環境
IRgbColor pColor = new RgbColor();
pColor.Red = 255;
pSelectionEnv.DefaultColor = pColor; //設置高亮顯示的顏色!

pMap.SelectByShape(pGeometry, pSelectionEnv, false); //選擇圖形!
axMapControl1.Refresh(esriViewDrawPhase.esriViewGeoSelection, null, null);
}

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A3個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:只顯示篩選的要素

---------------------------------------------------------------------------------------------------------

●·● IFeatureLayerDefinition 接口

---------------------------------------------------------------------------------------------------------

1. 通過 IFeatureLayerDefinition 接口的 DefinitionExpression 屬性可以實現!

IFeatureLayer pFeatureLayer = axMapControl1.Map.get_Layer(0) as IFeatureLayer;
IFeatureLayerDefinition pFeatLyrDef = pFeatureLayer as IFeatureLayerDefinition; //新建 IFeatureLayerDefinition 接口實例
pFeatLyrDef.DefinitionExpression = "Area > 20";  //定義篩選條件
axMapControl1.ActiveView.Refresh();  //刷新

這樣便只顯示符合要求的部分了!即面積大於20的要素!

2. 通過 IFeatureLayerDefinition 接口的 CreatSelectionLayer 方法可以通過篩選建立新圖層!

IFeatureLayer pFeatureLayer = axMapControl1.Map.get_Layer(0) as IFeatureLayer;
IFeatureLayerDefinition pFeatLyrDef = pFeatureLayer as IFeatureLayerDefinition;
pFeatLyrDef.DefinitionExpression = "Area > 20";
axMapControl1.ActiveView.Refresh(); //重新定義的圖層

IQueryFilter pQueryFilter = new QueryFilter();
pQueryFilter.WhereClause = "POP > 10";

IFeatureSelection pFeatSel = pFeatureLayer as IFeatureSelection;
pFeatSel.SelectFeatures(pQueryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
axMapControl1.Refresh(esriViewDrawPhase.esriViewGeoSelection, null, null);  //在新定義圖層的基礎上進行的查詢

IFeatureLayer pNewFeat = pFeatLyrDef.CreateSelectionLayer("New Layer", true, null, null);  //新建的圖層包括上面兩者的交集部分!
pFeatSel.Clear();
axMapControl1.Map.AddLayer(pNewFeat);
MessageBox.Show(axMapControl1.Map.LayerCount.ToString());

首先是建立一個虛擬的新圖層,然后在此新圖層的基礎上進行篩選,然后從而生成新的圖層!

參考:http://blog.csdn.net/qinyilang/article/details/6575539
---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A4個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:高亮顯示篩選的要素

---------------------------------------------------------------------------------------------------------

●·● IFeatureSelection 接口

---------------------------------------------------------------------------------------------------------

通過 IFeatureSelection 接口的 SelectFeatures 方法可以實現!

IFeatureLayer pFeatureLayer = axMapControl1.Map.get_Layer(0) as IFeatureLayer;
IQueryFilter pQueryFilter = new QueryFilter();  //建立查詢
pQueryFilter.WhereClause = "POP > 10";
IFeatureSelection pFeatSel = pFeatureLayer as IFeatureSelection;  //新建 IFeatureSelection 接口實例
pFeatSel.SelectFeatures(pQueryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);  //實現方法,選擇篩選的部分!
axMapControl1.Refresh(esriViewDrawPhase.esriViewGeoSelection, null, null);

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A5個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:類似 ArcMap 中 Identify 工具的效果

---------------------------------------------------------------------------------------------------------

●·● IIdentify 接口

---------------------------------------------------------------------------------------------------------

●·● IIdentifyObj 接口

---------------------------------------------------------------------------------------------------------

●·● IArray 接口

---------------------------------------------------------------------------------------------------------

主要實現點擊查詢並閃爍顯示,並把查詢要素的信息通過DataGridView顯示出來,主要用到的接口:IIdentity、IArray、IIdentifyObj

IIdentify pIdentify = axMapControl1.Map.get_Layer(0) as IIdentify; //通過圖層獲取 IIdentify 實例
IPoint pPoint = new ESRI.ArcGIS.Geometry.Point(); //新建點來選擇
IArray pIDArray;
IIdentifyObj pIdObj;

pPoint.PutCoords(e.mapX, e.mapY); //定義點
pIDArray = pIdentify.Identify(pPoint); //通過點獲取數組,用點一般只能選擇一個元素
if (pIDArray != null)
{
pIdObj = pIDArray.get_Element(0) as IIdentifyObj; //取得要素
pIdObj.Flash(axMapControl1.ActiveView.ScreenDisplay); //閃爍效果
MessageBox.Show("Layer: " + pIdObj.Layer.Name + "\n" + "Feature: " + pIdObj.Name); //輸出信息
}
else
{
MessageBox.Show("Nothing!");
}

效果:

框選實現如下所示:

IIdentify pIdentify = axMapControl1.Map.get_Layer(0) as IIdentify;
IGeometry pGeo = axMapControl1.TrackRectangle() as IGeometry;
IArray pIDArray;
IIdentifyObj pIdObj;

pIDArray = pIdentify.Identify(pGeo);
if (pIDArray != null)
{
string str = "\n";
string lyrName = "";
for (int i = 0; i < pIDArray.Count;i++ )
{
pIdObj = pIDArray.get_Element(i) as IIdentifyObj;
pIdObj.Flash(axMapControl1.ActiveView.ScreenDisplay);
str += pIdObj.Name + "\n";
lyrName = pIdObj.Layer.Name;
}
MessageBox.Show("Layer: " + lyrName + "\n" + "Feature: " + str);
}
else
{
MessageBox.Show("Nothing!");
}

效果如下:

參考:http://blog.csdn.net/mjhwy/article/details/7337426

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A6個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:在 MapControl 上繪制幾何圖形

可以直接使用 axMapControl1.DrawShape 方法來實現~!

ISimpleLineSymbol pLineSym = new SimpleLineSymbol();
IRgbColor pColor = new RgbColor();
pColor.Red = 11;
pColor.Green = 120;
pColor.Blue = 233;
pLineSym.Color = pColor;
pLineSym.Style = esriSimpleLineStyle.esriSLSSolid;
pLineSym.Width = 2;

IPolyline pLine = axMapControl1.TrackLine() as IPolyline;

object symbol = pLineSym as object;
axMapControl1.DrawShape(pLine, ref symbol);

也可以通過 IScreenDisplay 接口的方法來實現!~

ISimpleLineSymbol pLineSym = new SimpleLineSymbol();
IRgbColor pColor = new RgbColor();
pColor.Red = 11;
pColor.Green = 120;
pColor.Blue = 233;
pLineSym.Color = pColor;
pLineSym.Style = esriSimpleLineStyle.esriSLSSolid;
pLineSym.Width = 2;

IPolyline pLine = axMapControl1.TrackLine() as IPolyline;

IScreenDisplay pScreenDisplay = axMapControl1.ActiveView.ScreenDisplay;
pScreenDisplay.StartDrawing(pScreenDisplay.hDC, 1);
pScreenDisplay.SetSymbol(pLineSym as ISymbol);
pScreenDisplay.DrawPolyline(pLine);
pScreenDisplay.FinishDrawing();

通過比較,只是后面實現的部分不同,前面都是相同的!

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣   第A6A個   ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:在 MapControl 上繪制幾何圖形(IGraphicsContainer,幾何:圓)

  普通的圖形,可以直接向下面一樣實現!

m_ActiveView = m_hookHelper.ActiveView;
m_Map = m_hookHelper.FocusMap;
IScreenDisplay pScreenDisplay = m_ActiveView.ScreenDisplay;
IRubberBand pRubberPolygon = new RubberPolygonClass();
ISimpleFillSymbol pFillSymbol = new SimpleFillSymbolClass();
pFillSymbol.Color = getRGB(255, 255, 0);
IPolygon pPolygon = pRubberPolygon.TrackNew(pScreenDisplay, (ISymbol)pFillSymbol) as IPolygon;
pFillSymbol.Style = esriSimpleFillStyle.esriSFSDiagonalCross;
pFillSymbol.Color = getRGB(0, 255, 255);
IFillShapeElement pPolygonEle = new PolygonElementClass();
pPolygonEle.Symbol = pFillSymbol;
IElement pEle = pPolygonEle as IElement;
pEle.Geometry = pPolygon;
IGraphicsContainer pGraphicsContainer = m_Map as IGraphicsContainer;
pGraphicsContainer.AddElement(pEle, 0);
m_ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);

  畫圓比較特殊,因為沒有圓這個現成的幾何體,因此要轉換,如下所示:

m_ActiveView = m_hookHelper.ActiveView;
m_Map = m_hookHelper.FocusMap;
IScreenDisplay pScreenDisplay = m_ActiveView.ScreenDisplay;
IRubberBand pRubberCircle = new RubberCircleClass();
ISimpleFillSymbol pFillSymbol = new SimpleFillSymbolClass();
pFillSymbol.Color = getRGB(255, 255, 0);
IGeometry pCircle = pRubberCircle.TrackNew(pScreenDisplay, (ISymbol)pFillSymbol) as IGeometry;

IPolygon pPolygon = new PolygonClass();    //空的多邊形
ISegmentCollection pSegmentCollection = pPolygon as ISegmentCollection;  //段集合
ISegment pSegment = pCircle as ISegment;  //將圓賦值給段
object missing = Type.Missing;  //顯示默認值
pSegmentCollection.AddSegment(pSegment, ref missing, ref missing);  //給空多邊形加入圓
pFillSymbol.Style = esriSimpleFillStyle.esriSFSDiagonalCross;
pFillSymbol.Color = getRGB(0, 255, 255);
IFillShapeElement pPolygonEle = new PolygonElementClass();
pPolygonEle.Symbol = pFillSymbol;
IElement pEle = pPolygonEle as IElement;
pEle.Geometry = pPolygon;
IGraphicsContainer pGraphicsContainer = m_Map as IGraphicsContainer;
pGraphicsContainer.AddElement(pEle, 0);
m_ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);

 

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A7個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:在 MapControl 自由旋轉地圖

---------------------------------------------------------------------------------------------------------

●·● IScreenDisplay 接口

---------------------------------------------------------------------------------------------------------

通過 IScreenDisplay 接口來實現!

//鼠標按下!
private
void axMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
{
IPoint pPoint = new PointClass();
pPoint.PutCoords(e.mapX, e.mapY);
IPoint pCentrePoint = new PointClass();
pCentrePoint.PutCoords(axMapControl1.Extent.XMin + axMapControl1.ActiveView.Extent.Width / 2,
axMapControl1.Extent.YMax - axMapControl1.ActiveView.Extent.Height / 2); //獲取圖像的中心位置
axMapControl1.ActiveView.ScreenDisplay.RotateStart(pPoint, pCentrePoint); //開始旋轉
}
//鼠標移動!
private void axMapControl1_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
{
IPoint pPoint = new PointClass();
pPoint.PutCoords(e.mapX, e.mapY);
axMapControl1.ActiveView.ScreenDisplay.RotateMoveTo(pPoint); //旋轉到鼠標的位置
axMapControl1.ActiveView.ScreenDisplay.RotateTimer(); //可以忽略
}
//鼠標抬起!
private void axMapControl1_OnMouseUp(object sender, IMapControlEvents2_OnMouseUpEvent e)
{
double dRotationAngle = axMapControl1.ActiveView.ScreenDisplay.RotateStop(); //獲取旋轉的角度
axMapControl1.Rotation = dRotationAngle; //賦值給 axMapControl1.Rotation,這下真的旋轉了!
axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); //刷新!
}

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣   第A7A個   ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:在 MapControl 中鼠標與地圖反向移動

double startMapX = 0;
double startMapY = 0;
IScreenDisplay pScreenDisplay;

private void Form1_Load(object sender, EventArgs e)  //窗體加載信息
{
    pScreenDisplay = axMapControl1.ActiveView.ScreenDisplay;
}

private void axMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)  //鼠標按下的時候觸發
{
    IPoint pPoint = new PointClass();
    pPoint.PutCoords(e.mapX, e.mapY);
    pScreenDisplay.PanStart(pPoint);

    startMapY = e.mapY;
    startMapX = e.mapX;
}

private void axMapControl1_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)  //鼠標移動的時候觸發
{
    IPoint pPoint = new PointClass();
    pPoint.PutCoords(startMapX * 2 - e.mapX, startMapY * 2 - e.mapY);   //獲取當前點關於起始點的對稱點

    pScreenDisplay.PanMoveTo(pPoint);
}

private void axMapControl1_OnMouseUp(object sender, IMapControlEvents2_OnMouseUpEvent e)    //鼠標松開的時候觸發
{
    pScreenDisplay.PanStop();
}

 

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A8個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:彈出顏色選擇器

---------------------------------------------------------------------------------------------------------

●·● IColorPalette 接口

---------------------------------------------------------------------------------------------------------

1. ColorPalette:

private void button1_Click(object sender, EventArgs e)
{
    IColor pColor = new RgbColor();
    pColor.RGB = 255;
    tagRECT pTag = new tagRECT();
    pTag.left = this.Left + button1.Left + button1.Width;
    pTag.bottom = this.Top + button1.Top + button1.Height;
    IColorPalette pColorPalette = new ColorPalette();
    pColorPalette.TrackPopupMenu(ref pTag, pColor, false, 0);
    pColor = pColorPalette.Color;
}

效果:

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣   第A8A個   ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:獲取控件的屏幕位置(兩種方法)

第一種:將控件坐標轉換為屏幕坐標!

pTag.left = button1.PointToScreen(System.Drawing.Point.Empty).X;
pTag.bottom = button1.PointToScreen(System.Drawing.Point.Empty).Y + button1.Height;

第二種:通過空間之間屬性的間接計算!注:button1 在 groupBox2 中!

pTag.left = SystemInformation.FrameBorderSize.Width + this.Left + groupBox2.Left + button1.Left;
pTag.bottom = (this.Height - this.ClientRectangle.Height - SystemInformation.FrameBorderSize.Height) + this.Top + groupBox2.Top + button1.Top + button1.Height;

---------------------------------------------------------------------------------------------------------

●·● IColorSelector 接口

---------------------------------------------------------------------------------------------------------

2. ColorSelector:

IColor pColor = new RgbColor();
pColor.RGB = 255;
IColorSelector pSelector = new ColorSelectorClass();
pSelector.Color = pColor;
if (pSelector.DoModal(0))
{
    pColor = pSelector.Color;
}

效果:

---------------------------------------------------------------------------------------------------------

●·● IColorBrowser 接口

---------------------------------------------------------------------------------------------------------

3. ColorBrowser:

IColor pColor = new RgbColor();
pColor.RGB = 255;
IColorBrowser pColorBrowser = new ColorBrowser();
pColorBrowser.Color = pColor;
if (pColorBrowser.DoModal(0))
{
    pColor = pColorBrowser.Color;
}

效果:

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第A9個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:顏色台(Color Ramp)

---------------------------------------------------------------------------------------------------------

●·● IAlgorithmicColorRamp 接口

---------------------------------------------------------------------------------------------------------

1. AlgorithmicColorRamp:

定義函數:

private IEnumColors CreateColorRamp(IColor fromColor,IColor toColor,int count)
{
    IAlgorithmicColorRamp pRampColor = new AlgorithmicColorRamp();
    pRampColor.FromColor = fromColor;
    pRampColor.ToColor = toColor;
    pRampColor.Size = count;
    bool ok = false;
    pRampColor.CreateRamp(out ok);
    if (ok)
    {
        return pRampColor.Colors;
    }
    else
    {
        return null;
    }
}

調用函數:顏色在 red 和 violet 之間變化!

private void timer1_Tick(object sender, EventArgs e)
{
    IRgbColor fromColor = new RgbColor();
    fromColor.Red = 255;
    IRgbColor toColor = new RgbColor();
    toColor.Red = 128;
    toColor.Blue = 255;
    IEnumColors pEnumColors = CreateColorRamp(fromColor, toColor, 50);
    IColor pColor = null;
    for (int i = 0; i < count;i++ )
    {
        pColor = pEnumColors.Next();
    }
    if (count == 50)
    {
        count = 0;
        timer1.Enabled = false;
        timer2.Enabled = true;
    }
    count++;
    axPageLayoutControl1.PageLayout.Page.BackgroundColor = pColor;
}

private void timer2_Tick(object sender, EventArgs e)
{
    IRgbColor fromColor = new RgbColor();
    fromColor.Red = 128;
    fromColor.Blue = 255;
    IRgbColor toColor = new RgbColor();
    toColor.Red = 255;
    IEnumColors pEnumColors = CreateColorRamp(fromColor, toColor, 20);
    IColor pColor = null;
    for (int i = 0; i < count; i++)
    {
        pColor = pEnumColors.Next();
    }
    if (count == 20)
    {
        count = 0;
        timer2.Enabled = false;
        timer1.Enabled = true;
    }
    count++;
    axPageLayoutControl1.PageLayout.Page.BackgroundColor = pColor;
}

---------------------------------------------------------------------------------------------------------

●·● IRandomColorRamp 接口

---------------------------------------------------------------------------------------------------------

2. RandomColorRamp:

定義函數:

private IColor CreateRandomColorRamp()
{
    IRandomColorRamp pRandomColor = new RandomColorRamp();
    pRandomColor.StartHue = 140;
    pRandomColor.EndHue = 220;
    pRandomColor.MinValue = 35;
    pRandomColor.MaxValue = 100;
    pRandomColor.MinSaturation = 32;
    pRandomColor.MaxSaturation = 100;

    pRandomColor.Size = 12;
    pRandomColor.Seed = 7;
    bool ok = true;
    pRandomColor.CreateRamp(out ok);
    IEnumColors pEnumColors = pRandomColor.Colors;
    IColor pColor = pEnumColors.Next();
    return pColor;
}

調用函數

private void button5_Click(object sender, EventArgs e)
{
    IColor pColor = CreateRandomColorRamp();
    axPageLayoutControl2.PageLayout.Page.BackgroundColor = pColor;
} 

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第G1個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:Symbol 對象

---------------------------------------------------------------------------------------------------------

●·● ISimpleMarkerSymbol 接口

---------------------------------------------------------------------------------------------------------

1. SimpleMarkerSymbol:

新建工具!

using System;
using System.Drawing;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.Controls;
using System.Windows.Forms;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geometry;

namespace Symbol
{
    /// <summary>
    /// Summary description for Tool1.
    /// </summary>
    [Guid("63835a8e-ae77-4817-b4e4-3b120b5232f9")]
    [ClassInterface(ClassInterfaceType.None)]
    [ProgId("Symbol.Tool1")]
    public sealed class Tool1 : 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 = null; private IMapControl4 pMapControl; //---------------------------------------------------------------------------------------------------------
public Tool1() { // // TODO: Define values for the public properties // base.m_category = "Marker"; //localizable text base.m_caption = "Marker"; //localizable text base.m_message = "Marker"; //localizable text base.m_toolTip = "Marker"; //localizable text base.m_name = "Marker"; //unique id, non-localizable (e.g. "MyCategory_MyTool") try { // // TODO: change resource name if necessary // string bitmapResourceName = GetType().Name + ".bmp"; base.m_bitmap = new Bitmap(GetType(), bitmapResourceName); base.m_cursor = new System.Windows.Forms.Cursor(GetType(), GetType().Name + ".cur"); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap"); } } #region Overriden Class Methods /// <summary> /// Occurs when this tool is created /// </summary> /// <param name="hook">Instance of the application</param> public override void OnCreate(object hook) { if (m_hookHelper == null) m_hookHelper = new HookHelperClass(); m_hookHelper.Hook = hook;
//---------------------------------------------------------------------------------------------------------
if (hook is IMapControl4) { pMapControl = hook as IMapControl4; } //---------------------------------------------------------------------------------------------------------
// TODO: Add Tool1.OnCreate implementation } /// <summary> /// Occurs when this tool is clicked /// </summary> public override void OnClick() { // TODO: Add Tool1.OnClick implementation } public override void OnMouseDown(int Button, int Shift, int X, int Y) { // TODO: Add Tool1.OnMouseDown implementation

//---------------------------------------------------------------------------------------------------------
ISimpleMarkerSymbol pMarkerSymbol = new SimpleMarkerSymbol(); pMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSCross; pMarkerSymbol.Color = GetColor(255, 0, 0); pMarkerSymbol.Size = 16; pMarkerSymbol.Outline = true; pMarkerSymbol.OutlineSize = 4; pMarkerSymbol.OutlineColor = GetColor(0, 255, 0); IPoint pPoint = pMapControl.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y); object oMarkerSymbol = pMarkerSymbol; pMapControl.DrawShape(pPoint, ref oMarkerSymbol); //---------------------------------------------------------------------------------------------------------
}
//---------------------------------------------------------------------------------------------------------
private IRgbColor GetColor(int r,int g,int b) { IRgbColor pColor = new RgbColor(); pColor.Red = r; pColor.Green = g; pColor.Blue = b; return pColor; }
//---------------------------------------------------------------------------------------------------------
public override void OnMouseMove(int Button, int Shift, int X, int Y) { // TODO: Add Tool1.OnMouseMove implementation } public override void OnMouseUp(int Button, int Shift, int X, int Y) { // TODO: Add Tool1.OnMouseUp implementation } #endregion } }

調用:

        private void button1_Click(object sender, EventArgs e)
        {
            ICommand command = new Symbol.Tool1();
            command.OnCreate(axMapControl1.Object);
            axMapControl1.CurrentTool = command as ESRI.ArcGIS.SystemUI.ITool;
        }

---------------------------------------------------------------------------------------------------------

●·● IArrowMarkerSymbol 接口

---------------------------------------------------------------------------------------------------------

2. ArrowMarkerSymbol:

public override void OnMouseDown(int Button, int Shift, int X, int Y)
{
    // TODO:  Add AddArrow.OnMouseDown implementation
    IArrowMarkerSymbol pArrowMarkerSymbol = new ArrowMarkerSymbol();
    pArrowMarkerSymbol.Style = esriArrowMarkerStyle.esriAMSPlain;
    pArrowMarkerSymbol.Color = GetColor(55, 111, 255);
    pArrowMarkerSymbol.Length = 20;
    pArrowMarkerSymbol.Angle = 90;
    pArrowMarkerSymbol.Width = 10;
    IPoint pPoint = pMapControl.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
    object symbol = pArrowMarkerSymbol;
    pMapControl.DrawShape(pPoint, ref symbol);
} 

---------------------------------------------------------------------------------------------------------

●·● ICharacterMarkerSymbol 接口

---------------------------------------------------------------------------------------------------------

●·● stdole.StdFont

---------------------------------------------------------------------------------------------------------

3. CharacterMarkerSymbol:

public override void OnMouseDown(int Button, int Shift, int X, int Y)
{
    // TODO:  Add Character.OnMouseDown implementation
    stdole.StdFont pFont = new stdole.StdFont();       //新建字體!
    pFont.Name = "ESRI Default Marker";
    pFont.Size = 37;
    pFont.Italic = true;

    ICharacterMarkerSymbol pCharacterSymbol = new CharacterMarkerSymbol();
    pCharacterSymbol.CharacterIndex = 60;
    pCharacterSymbol.Color = GetColor(0, 0, 255);
    pCharacterSymbol.Size = 25;
    IPoint pPoint = pMapControl.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
    object oCharMarkerSymbol = pCharacterSymbol;
    pMapControl.DrawShape(pPoint, ref oCharMarkerSymbol);
}

---------------------------------------------------------------------------------------------------------

●·● IPictureMarkerSymbol 接口

---------------------------------------------------------------------------------------------------------

4. PictureMarkerSymbol:

public override void OnMouseDown(int Button, int Shift, int X, int Y)
{
       // TODO:  Add Character.OnMouseDown implementation
       IPictureMarkerSymbol pPictureSymbol = new PictureMarkerSymbol();
            pPictureSymbol.CreateMarkerSymbolFromFile(esriIPictureType.esriIPictureBitmap, @"F:\Desktop\1.bmp");
            pPictureSymbol.Size = 80;
            pPictureSymbol.BitmapTransparencyColor = GetColor(255, 255, 255);

            IPoint pPoint = pMapControl1.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(e.x, e.y);
            object oMarkerSymbol = pPictureSymbol;
            pMapControl1.DrawShape(pPoint, ref oMarkerSymbol);
}

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第G2個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:顯示圖層的屬性窗口

首先新建 Command,下面是實現代碼的重要部分!

 

private bool SetupFeaturePropertySheet(ILayer layer)
{
    if (layer == null) return false;
    ESRI.ArcGIS.Framework.IComPropertySheet pComPropSheet;
    pComPropSheet = new ESRI.ArcGIS.Framework.ComPropertySheet();
    pComPropSheet.Title = layer.Name + " - 屬性";

    ESRI.ArcGIS.esriSystem.UID pPPUID = new ESRI.ArcGIS.esriSystem.UIDClass();
    pComPropSheet.AddCategoryID(pPPUID);

    // General....
    ESRI.ArcGIS.Framework.IPropertyPage pGenPage = new ESRI.ArcGIS.CartoUI.GeneralLayerPropPageClass();
    pComPropSheet.AddPage(pGenPage);

    // Source
    ESRI.ArcGIS.Framework.IPropertyPage pSrcPage = new ESRI.ArcGIS.CartoUI.FeatureLayerSourcePropertyPageClass();
    pComPropSheet.AddPage(pSrcPage);

    // Selection...
    ESRI.ArcGIS.Framework.IPropertyPage pSelectPage = new ESRI.ArcGIS.CartoUI.FeatureLayerSelectionPropertyPageClass();
    pComPropSheet.AddPage(pSelectPage);

    // Display....
    ESRI.ArcGIS.Framework.IPropertyPage pDispPage = new ESRI.ArcGIS.CartoUI.FeatureLayerDisplayPropertyPageClass();
    pComPropSheet.AddPage(pDispPage);

    // Symbology....
    ESRI.ArcGIS.Framework.IPropertyPage pDrawPage = new ESRI.ArcGIS.CartoUI.LayerDrawingPropertyPageClass();
    pComPropSheet.AddPage(pDrawPage);

    // Fields... 
    ESRI.ArcGIS.Framework.IPropertyPage pFieldsPage = new ESRI.ArcGIS.CartoUI.LayerFieldsPropertyPageClass();
    pComPropSheet.AddPage(pFieldsPage);

    // Definition Query... 
    ESRI.ArcGIS.Framework.IPropertyPage pQueryPage = new ESRI.ArcGIS.CartoUI.LayerDefinitionQueryPropertyPageClass();
    pComPropSheet.AddPage(pQueryPage);

    // Labels....
    ESRI.ArcGIS.Framework.IPropertyPage pSelPage = new ESRI.ArcGIS.CartoUI.LayerLabelsPropertyPageClass();
    pComPropSheet.AddPage(pSelPage);

    // Joins & Relates....
    ESRI.ArcGIS.Framework.IPropertyPage pJoinPage = new ESRI.ArcGIS.ArcMapUI.JoinRelatePageClass();
    pComPropSheet.AddPage(pJoinPage);

    // Setup layer link
    ESRI.ArcGIS.esriSystem.ISet pMySet = new ESRI.ArcGIS.esriSystem.SetClass();
    pMySet.Add(layer);
    pMySet.Reset();

    // make the symbology tab active
    pComPropSheet.ActivePage = 4;

    // show the property sheet
    bool bOK = pComPropSheet.EditProperties(pMySet, 0);

    m_activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, m_activeView.Extent);
    return (bOK);
}

 

完整實現的 Command 代碼如下:

View Code
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Carto;
using System.Windows.Forms;

namespace ControlsApplication
{
    /// <summary>
    /// Command that works in ArcMap/Map/PageLayout
    /// </summary>
    [Guid("28a91291-f3b1-4246-9034-86598eb78cca")]
    [ClassInterface(ClassInterfaceType.None)]
    [ProgId("ControlsApplication.LayerPropertiesCmd")]
    public sealed class LayerPropertiesCmd : BaseCommand
    {
        #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);
            MxCommands.Register(regKey);
            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);
            MxCommands.Unregister(regKey);
            ControlsCommands.Unregister(regKey);
        }

        #endregion
        #endregion

        private IHookHelper m_hookHelper = null;
        IActiveView m_activeView = null;
        IMapControl3 m_mapcontrol = null;
        IFeatureLayer currentLayer = null;

        public LayerPropertiesCmd()
        {
            base.m_category = "ControlsApplication";
            base.m_caption = "圖層屬性";
            base.m_message = "圖層屬性";
            base.m_toolTip = "圖層屬性";
            base.m_name = "LayerPropertiesCmd";
            base.m_enabled = true;

            try
            {
                string bitmapResourceName = GetType().Name + ".bmp";
                base.m_bitmap = new Bitmap(GetType(), bitmapResourceName);
            }
            catch (Exception ex)
            {
                MessageBox.Show("無效位圖!!" + ex.Message, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        #region Overridden Class Methods

        /// <summary>
        /// Occurs when this command is created
        /// </summary>
        /// <param name="hook">Instance of the application</param>
        public override void OnCreate(object hook)
        {
            if (hook == null)
                return;

            m_hookHelper = new HookHelperClass();
            m_hookHelper.Hook = hook;           
        }

        /// <summary>
        /// Occurs when this command is clicked
        /// </summary>
        public override void OnClick()
        {
            if (m_hookHelper.Hook is IToolbarControl)
            {
                IToolbarControl toolbarControl = m_hookHelper.Hook as IToolbarControl;
                m_mapcontrol = (IMapControl3)toolbarControl.Buddy;
            }
            if (m_hookHelper.Hook is IMapControl3)
            {
                m_mapcontrol = m_hookHelper.Hook as IMapControl3;
            }
            if (m_mapcontrol != null)
            {
                currentLayer = m_mapcontrol.CustomProperty as IFeatureLayer;
                m_activeView = m_mapcontrol.ActiveView;
            }

            if (currentLayer == null) return;
            SetupFeaturePropertySheet(currentLayer);
        }

        #endregion
        private bool SetupFeaturePropertySheet(ILayer layer)
        {
            if (layer == null) return false;
            ESRI.ArcGIS.Framework.IComPropertySheet pComPropSheet;
            pComPropSheet = new ESRI.ArcGIS.Framework.ComPropertySheet();
            pComPropSheet.Title = layer.Name + " - 屬性";

            ESRI.ArcGIS.esriSystem.UID pPPUID = new ESRI.ArcGIS.esriSystem.UIDClass();
            pComPropSheet.AddCategoryID(pPPUID);

            // General....
            ESRI.ArcGIS.Framework.IPropertyPage pGenPage = new ESRI.ArcGIS.CartoUI.GeneralLayerPropPageClass();
            pComPropSheet.AddPage(pGenPage);

            // Source
            ESRI.ArcGIS.Framework.IPropertyPage pSrcPage = new ESRI.ArcGIS.CartoUI.FeatureLayerSourcePropertyPageClass();
            pComPropSheet.AddPage(pSrcPage);

            // Selection...
            ESRI.ArcGIS.Framework.IPropertyPage pSelectPage = new ESRI.ArcGIS.CartoUI.FeatureLayerSelectionPropertyPageClass();
            pComPropSheet.AddPage(pSelectPage);

            // Display....
            ESRI.ArcGIS.Framework.IPropertyPage pDispPage = new ESRI.ArcGIS.CartoUI.FeatureLayerDisplayPropertyPageClass();
            pComPropSheet.AddPage(pDispPage);

            // Symbology....
            ESRI.ArcGIS.Framework.IPropertyPage pDrawPage = new ESRI.ArcGIS.CartoUI.LayerDrawingPropertyPageClass();
            pComPropSheet.AddPage(pDrawPage);

            // Fields... 
            ESRI.ArcGIS.Framework.IPropertyPage pFieldsPage = new ESRI.ArcGIS.CartoUI.LayerFieldsPropertyPageClass();
            pComPropSheet.AddPage(pFieldsPage);

            // Definition Query... 
            ESRI.ArcGIS.Framework.IPropertyPage pQueryPage = new ESRI.ArcGIS.CartoUI.LayerDefinitionQueryPropertyPageClass();
            pComPropSheet.AddPage(pQueryPage);

            // Labels....
            ESRI.ArcGIS.Framework.IPropertyPage pSelPage = new ESRI.ArcGIS.CartoUI.LayerLabelsPropertyPageClass();
            pComPropSheet.AddPage(pSelPage);

            // Joins & Relates....
            ESRI.ArcGIS.Framework.IPropertyPage pJoinPage = new ESRI.ArcGIS.ArcMapUI.JoinRelatePageClass();
            pComPropSheet.AddPage(pJoinPage);

            // Setup layer link
            ESRI.ArcGIS.esriSystem.ISet pMySet = new ESRI.ArcGIS.esriSystem.SetClass();
            pMySet.Add(layer);
            pMySet.Reset();

            // make the symbology tab active
            pComPropSheet.ActivePage = 4;

            // show the property sheet
            bool bOK = pComPropSheet.EditProperties(pMySet, 0);

            m_activeView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, m_activeView.Extent);

            ////更新圖例
            //IMapSurround pMapSurround = null;
            //ILegend pLegend = null;

            //for (int i = 0; i < m_map.MapSurroundCount; i++)
            //{
            //    pMapSurround = m_map.get_MapSurround(i);
            //    if (pMapSurround is ILegend)
            //    {
            //        pLegend = pMapSurround as ILegend;
            //        pLegend.AutoVisibility = true;
            //        pLegend.Refresh();

            //    }
            //}

            return (bOK);
        }
    }
}

 

效果如下所示:

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第G3個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:PageLayoutControl 的樣式設置

Border:

IActiveView pActiveView = axPageLayoutControl1.PageLayout as IActiveView;
IMap pMap = pActiveView.FocusMap;
IGraphicsContainer pGraphicsContainer = pActiveView as IGraphicsContainer;
IMapFrame pMapFrame = pGraphicsContainer.FindFrame(pMap) as IMapFrame;
IStyleSelector pStyleSelector = new BorderSelector();
if (pStyleSelector.DoModal(axPageLayoutControl1.hWnd))
{
    IBorder PBorder = pStyleSelector.GetStyle(0) as IBorder;
    pMapFrame.Border = PBorder;
}
axPageLayoutControl1.Refresh(esriViewDrawPhase.esriViewBackground, null, null);

 

Background:

IActiveView pActiveView = axPageLayoutControl1.PageLayout as IActiveView;
IMap pMap = pActiveView.FocusMap;
IGraphicsContainer pGraphicsContainer = pActiveView as IGraphicsContainer;
IMapFrame pMapFrame = pGraphicsContainer.FindFrame(pMap) as IMapFrame;
IStyleSelector pStyleSelector = new BackgroundSelector();
if (pStyleSelector.DoModal(axPageLayoutControl1.hWnd))
{
    IBackground pBackground = pStyleSelector.GetStyle(0) as IBackground;
    pMapFrame.Background = pBackground;
}
pActiveView.Refresh();

 

Shadow:

IActiveView pActiveView = axPageLayoutControl1.PageLayout as IActiveView;
IMap pMap = pActiveView.FocusMap;
IGraphicsContainer pGraphicsContainer = pActiveView as IGraphicsContainer;
IMapFrame pMapFrame = pGraphicsContainer.FindFrame(pMap) as IMapFrame;
IStyleSelector pStyleSelector = new ShadowSelector();
if (pStyleSelector.DoModal(axPageLayoutControl1.hWnd))
{
    IShadow pShadow = pStyleSelector.GetStyle(0) as IShadow;
    IFrameProperties pFrameProperties = pMapFrame as IFrameProperties;
    pFrameProperties.Shadow = pShadow;
}
pActiveView.Refresh();

 

MapGrid:

IActiveView pActiveView = axPageLayoutControl1.PageLayout as IActiveView;
IMap pMap = pActiveView.FocusMap;
IGraphicsContainer pGraphicsContainer = pActiveView as IGraphicsContainer;
IMapFrame pMapFrame = pGraphicsContainer.FindFrame(pMap) as IMapFrame;
IStyleSelector pStyleSelector = new MapGridSelector();
if (pStyleSelector.DoModal(axPageLayoutControl1.hWnd))
{
    IMapGrid pMapGrid = pStyleSelector.GetStyle(0) as IMapGrid;
    IMapGrids pMapGrids = pMapFrame as IMapGrids;
    if (pMapGrid == null)
    {
        return;
    }
    pMapGrids.AddMapGrid(pMapGrid);
}
pActiveView.Refresh();

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第G4個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:刪除shapefile文件中的重復數據

第一種情況,只是出現重復數據,那么可以通過判斷某一個字段值是否一樣來進行刪除重復的部分,實現如下:

IFeatureLayer pFeatureLayer = axMapControl1.get_Layer(0) as IFeatureLayer;
IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
IFeatureCursor pFeatureCursor = pFeatureClass.Search(null, false);
IFeature pFeature = pFeatureCursor.NextFeature();
int count = 1;
while (pFeature != null)
{
string name = pFeature.get_Value(pFeatureClass.FindField("Name")).ToString(); //首先獲取Name字段的名稱屬性
while (pFeature != null) //外層遍歷
{
pFeature = pFeatureCursor.NextFeature(); //開始檢查下一個要素與目標要素的關系
if (pFeature == null) //若已經沒有了,則終止
break; //跳出
string findName = pFeature.get_Value(pFeatureClass.FindField("Name")).ToString();
if (findName == name) //若名稱相同,則刪除此要素
pFeature.Delete();
}
pFeatureCursor = pFeatureClass.Search(null, false); //重新從頭開始
for (int i = 0; i <= count;i++ ) //為了獲取比上一個目標要素下一個的目標,通過count來遍歷
pFeature = pFeatureCursor.NextFeature();
count++; //每執行一次操作,增加一次count
}

第二種情況,不僅出現某些屬性,例如Name相同,但是幾何體不是相同的,其中的一部分是殘缺的,這個時候就要動用Area了,因為只有最大的那個Area才是完整的,因此要刪除掉其他小的部分,可以按照如下實現:

IFeatureLayer pFeatureLayer = axMapControl1.get_Layer(0) as IFeatureLayer;
IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
IFeatureCursor pFeatureCursor = pFeatureClass.Search(null, false);
IFeature pFeature = pFeatureCursor.NextFeature();
int count = 1;
while (pFeature != null)
{
string name = pFeature.get_Value(pFeatureClass.FindField("Name")).ToString(); //首先獲取Name字段的名稱屬性
double area = Convert.ToDouble(pFeature.get_Value(pFeatureClass.FindField("Area"))); //獲取Area的大小
while (pFeature != null) //外層遍歷
{
pFeature = pFeatureCursor.NextFeature(); //開始檢查下一個要素與目標要素的關系
if (pFeature == null) //若已經沒有了,則在從頭開始
{
pFeatureCursor = pFeatureClass.Search(null, false); //重新從頭開始
pFeature = pFeatureCursor.NextFeature();
}
string findName = pFeature.get_Value(pFeatureClass.FindField("Name")).ToString();
double findArea = Convert.ToDouble(pFeature.get_Value(pFeatureClass.FindField("Area")));
if (findName == name && findArea < area) //若名稱相同,且面積小的時候才刪除,大的話就pass
pFeature.Delete();
else if (findName == name && findArea == area) //要是相同,則說明又碰到自己了,證明已經一圈過去了
break;
}
pFeatureCursor = pFeatureClass.Search(null, false); //重新從頭開始
for (int i = 0; i <= count;i++ ) //為了獲取比上一個目標要素下一個的目標,通過count來遍歷
pFeature = pFeatureCursor.NextFeature();
count++; //每執行一次操作,增加一次count
}

實現的代碼可能不是最好的,是自己寫的,要是數據很亂,就連最大的也是重復的,那就比較亂了,可以先試着下面的,將小的盡量刪光,然后在用上面的將重復的刪光!

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第G5個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:MapControl 與 PageLayoutControl 的交互

在 MapControl 和 PageLayoutControl 中進行關聯!

首先要認清一點,雖然 MapControl 和 PageLayoutControl 中都有 ActiveView 屬性,但是同樣的屬性在兩者中表示的含義不同,在 MapControl 中,ActiveView 與 FocusMap 基本是同樣的含義,是針對當前地圖的;而 PageLayoutControl 中,ActiveView 指的是當前的布局圖,並非 FocusMap,所以對於 MapControl 與 PageLayoutControl 之間的關聯要用到 PageLayoutControl 中的 FocusMap,而非 ActiveView,對於 MapControl 則無所謂。它們之間的不同,可以通過顯示其 Width 屬性來實現,如下所示:

private void button2_Click(object sender, EventArgs e)
{
label1.Text = axPageLayoutControl1.ActiveView.Extent.Width.ToString();
IActiveView pActiveView = axPageLayoutControl1.ActiveView.FocusMap as IActiveView;
label2.Text = pActiveView.Extent.Width.ToString();
}

private void button3_Click(object sender, EventArgs e)
{
label3.Text = axMapControl1.ActiveView.Extent.Width.ToString();
label4.Text = (axMapControl1.ActiveView.FocusMap as IActiveView).Extent.Width.ToString();
}

顯示如下:

由此可見,PageLayoutControl 的 ActiveView 是獨樹一幟的!

//當地圖替換的時候觸發

private
void axMapControl1_OnMapReplaced(object sender, IMapControlEvents2_OnMapReplacedEvent e)
{
IObjectCopy pObjectCopy = new ObjectCopy();
object copyMap = axMapControl1.Map;
object overWriteMap = axPageLayoutControl1.ActiveView.FocusMap;
pObjectCopy.Overwrite(copyMap, ref overWriteMap);
}

//當布局的地圖發生變化的時候觸發,將 axPageLayoutControl 中地圖的范圍傳遞給 axMapControl

private void axPageLayoutControl1_OnAfterScreenDraw(object sender, IPageLayoutControlEvents_OnAfterScreenDrawEvent e)
{
IActiveView activeView = axPageLayoutControl1.ActiveView.FocusMap as IActiveView;
IDisplayTransformation displayTransformation = activeView.ScreenDisplay.DisplayTransformation;
axMapControl1.Extent = displayTransformation.VisibleBounds;
axMapControl1.ActiveView.Refresh();
}

//當地圖控件的范圍發生變化時,將 axMapControl 中地圖的范圍傳遞給axPageLayoutControl

private void axMapControl1_OnAfterDraw(object sender, IMapControlEvents2_OnAfterDrawEvent e)
{
IActiveView activeView = axPageLayoutControl1.ActiveView.FocusMap as IActiveView;
IDisplayTransformation displayTransformation = activeView.ScreenDisplay.DisplayTransformation;
displayTransformation.VisibleBounds = axMapControl1.Extent;
axPageLayoutControl1.ActiveView.Refresh();
}

另外,在 PageLayoutControl 中要想操作地圖,還是要用到地圖中的放大、縮小等工具,而要操作 PageLayoutControl 的框架時,則要用 PageLayout 的放大、縮小等工具!

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第G6個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:制作可以浮動的工具欄

第一步:導入一個類文件包,如下所示:

文件包下載>>>點擊下載<<<

  • 在 項目 上右鍵選擇 新建項》文件夾,命名為“rpaulo”,貌似是作者的名字!
  • 再在 此文件夾 下添加另外一個文件夾,命名為“toolbar”。
  • 然后 通過 添加》現有項,導航到文件夾中的 *.cs 和 *.resx 文件,將其全部倒入。

第二步:可以寫代碼了:

using rpaulo.toolbar;            //添加引用

ToolBarManager _toolBarManager;
_toolBarManager = new ToolBarManager(this, this);         //新建工具管理

// The control Text property is used to draw the bar name while floating
// and on view/hide menu.
_toolBar1.Text = "Bar #1";
_toolBar2.Text = "Bar #2";
_toolBar3.Text = "Bar #3";
_toolBar4.Text = "Bar #4";

// Add toolbar (default position)
_toolBarManager.AddControl(_toolBar1);
// Add toolbar (floating)
_toolBarManager.AddControl(_toolBar2, DockStyle.None);
// Add toolbar (left)
_toolBarManager.AddControl(_toolBar3, DockStyle.Left);
// Add toolbar (left, on the left of _toolBar3)
_toolBarManager.AddControl(_toolBar4, DockStyle.Left, _toolBar3, DockStyle.Left);
// Add control
ToolBarDockHolder holder = _toolBarManager.AddControl(_dateTimePicker, DockStyle.Bottom); 
// Added by mav
holder.ToolbarTitle = "Appointment";
holder.AllowedBorders = AllowedBorders.Top|AllowedBorders.Bottom;
_toolBarManager.AddControl(toolBar1, DockStyle.Right);
  • 可以將所有的控件都加進去,都可以實現浮動的效果,但是 toolbar 可以根據“左右上下”進行調整,移動到左右的時候自動變成垂直工具條!
  • 可能默認的情況沒有 ToolBar 控件,可以在 工具箱 上點擊右鍵,選擇 選擇項,找到后,選中即可使用了!

效果圖:

最重要的是那些代碼了,調用其實很容易的!

---------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第G7個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:ArcGIS Engine 實現鷹眼 & 分析

主要用到兩個 MapControl 的事件:

  1> OnExtentUpdated:實現地圖范圍變化時觸發。

  2> OnMouseDown:鼠標單擊的時候觸發。

第一步:實現 TrackRectangle 方法,通過拖拽矩形來放大地圖。

        private void axMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
{
IEnvelope pEnv = axMapControl1.TrackRectangle();
axMapControl1.Extent = pEnv;
}

第二步:實現信息從 MapControl1 傳遞到 MapControl2 中。

        private void axMapControl1_OnExtentUpdated(object sender, IMapControlEvents2_OnExtentUpdatedEvent e)
{
    //實現鷹眼的方框的 symbol 部分
ILineSymbol outLineSymbol = new SimpleLineSymbol();  //設置鷹眼圖中的紅線!
outLineSymbol.Width = 2;
outLineSymbol.Color = GetColor(255, 0, 0, 255);

IFillSymbol fillSymbol = new SimpleFillSymbol();  //設置填充符號的屬性!
fillSymbol.Color = GetColor(255, 0, 0, 0);   //設置完全透明色
fillSymbol.Outline = outLineSymbol;

    //實現信息傳遞
IEnvelope envlope2 = e.newEnvelope as IEnvelope;  //定義新的信封范圍,賦值為拖拽的矩形,或是extent
IElement element2 = new RectangleElement();  //定義一個要素,用在后面放在容器中顯示應眼框
element2.Geometry = envlope2;  //給矩形要素賦值上面的信封范圍

IFillShapeElement fillShapeElement2 = element2 as IFillShapeElement;  //具有 symbol 屬性!
fillShapeElement2.Symbol = fillSymbol;  //賦值上面定義的 symbol

IGraphicsContainer graphicsContainer2 = axMapControl2.Map as IGraphicsContainer;  //定義存儲圖形的容器
graphicsContainer2.DeleteAllElements();            //首先刪除當前的全部圖形,也就是上一次的鷹眼框
pElement = fillShapeElement2 as IElement;  //將 fillShapeElement2 在轉為 IElement,以為后面方法只能用這個類型!
graphicsContainer2.AddElement(pElement, 0);  //增加新的鷹眼框
axMapControl2.Refresh(esriViewDrawPhase.esriViewGeography, null, null);  //刷新 MapControl2
}

        private IRgbColor GetColor(int r, int g, int b, int t)  //定義獲取顏色的函數
        {
            IRgbColor rgbColor = new RgbColor();
            rgbColor.Red = r;
            rgbColor.Green = g;
            rgbColor.Blue = b;
            rgbColor.Transparency = (byte)t;  //透明度
            return rgbColor;
        }

第三步:實現點擊 MapControl2 響應鷹眼框的移動。

        private void axMapControl2_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
{
IPoint point = new ESRI.ArcGIS.Geometry.Point();  //定義地理點
point.PutCoords(e.mapX, e.mapY);    //獲取點擊的地理點
axMapControl1.CenterAt(point);  
}

效果顯示:

-------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第G8個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:獨立窗口的鷹眼顯示

№1:建立獨立顯示的窗體 Overview,在窗體中加入一個 MapControl 控件!

注意:將 axMapControl1 的 modifier 設置為 public,這樣在主窗體中才可以調用!

public partial class Overview : Form
{
    IMapControl4 m_mapControl;  //建立用於顯示主窗體 MapControl 的實例!
    IMap m_map;
    public Overview(IHookHelper hook)  //添加參數,用於與主窗體中 MapControl 相關聯!
    {
        InitializeComponent();
        m_mapControl = hook.Hook as IMapControl4;  //從 hook 中獲取主窗體的 MapControl!
        m_map = m_mapControl.Map;
    }

    private void Overview_Load(object sender, EventArgs e)
    {
        for (int i = m_map.LayerCount - 1; i >= 0;i-- )
        {
            axMapControl1.AddLayer(m_mapControl.get_Layer(i));
        }
        axMapControl1.Extent = m_mapControl.FullExtent;
    }

    private void axMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
    {
        IPoint centerPoint = new ESRI.ArcGIS.Geometry.Point();
        centerPoint.PutCoords(e.mapX, e.mapY);
        m_mapControl.CenterAt(centerPoint);
    }
}

№2:在主窗體中寫入交互內容!

private Overview pOverview2;  //實例化一個鷹眼窗口

private void button2_Click(object sender, EventArgs e)
{
    HookHelper hookHelper = new HookHelper();  //新建 HookHelper 的實例!
    hookHelper.Hook = axMapControl2.Object;  //將主窗體的 axMapControl1 賦值給其屬性 Hook,實現關聯!
    pOverview2 = new Overview(hookHelper);  //實例化一個鷹眼窗體,並將 hookHelper 傳遞過去!
    pOverview2.Show();  //窗體顯示!
}

private void axMapControl2_OnExtentUpdated(object sender, IMapControlEvents2_OnExtentUpdatedEvent e)
{
    IEnvelope pEnv = e.newEnvelope as IEnvelope;  //獲取矩形
    IGraphicsContainer pGraphicsContainer = pOverview2.axMapControl1.Map as IGraphicsContainer;  //在鷹眼窗體上建立容器
    IActiveView pActiveView = pGraphicsContainer as IActiveView;  //用於刷新的
    pGraphicsContainer.DeleteAllElements();  //刪除所有圖形

    ISimpleLineSymbol pSimpleLineSymbol = new SimpleLineSymbol();  //新建線狀樣式
    IRgbColor pColor = new RgbColor();
    pColor.Red = 255;
    pSimpleLineSymbol.Width = 1;
    pSimpleLineSymbol.Color = pColor;

    ISimpleFillSymbol pSimpleFillSymbol = new SimpleFillSymbol();  //新建填充樣式
    IRgbColor pColor2 = new RgbColor();
    pColor2.Transparency = 0;
    pSimpleFillSymbol.Color = pColor2;
    pSimpleFillSymbol.Outline = pSimpleLineSymbol;

    IElement pElement = new RectangleElement();  //新建元素,用於后面添加到地圖上面的
    pElement.Geometry = pEnv;  //給元素賦予幾何(矩形)屬性,因為不具有 Symbol 屬性,所以還要 QI 一下

    IFillShapeElement pFillShapeElement = pElement as IFillShapeElement;  //用於賦予 symbol 的內容
    pFillShapeElement.Symbol = pSimpleFillSymbol;  
pElement
= pFillShapeElement as IElement;  //后面方法中只能用 IElement,所以在轉回來!
pGraphicsContainer.AddElement(pElement,
0);  //添加元素,實現鷹眼效果
pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics,
null, null);  //刷新,這是刷新的鷹眼窗體! }

效果如下圖所示:

-------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第G9個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:自定義工具窗口

---------------------------------------------------------------------------------------------------------

●·● ICustomizeDialog 接口

  Members

    Description
Method CloseDialog Closes the customize dialog.
Read/write property CommandsCategory The GUID of the component category used for commands.
Read/write property DialogTitle The title of the customize dialog.
Read-only property DoubleClickDestination The ToolbarControl commands are added to when double clicked.
Read-only property IsDialogActive Indicates if the customize dialog is active on the screen.
Read/write property MenusCategory The GUID of the component category used for menu definitions.
Method SetDoubleClickDestination Sets the ToolbarControl commands are added to when double clicked.
Read/write property ShowAddFromFile Indicates if the 'Add From File' button is available on the customize dialog.
Method StartDialog Starts the modeless customize dialog.
Read/write property ToolbarsCategory The GUID of the component category used for toolbar definitions.

---------------------------------------------------------------------------------------------------------

●·● ICustomizeDialogEvents 接口

  Members

    Description
Event OnCloseDialog Fires when customize dialog is closed or exited.
Event OnStartDialog Fires when customize dialog is displayed on screen.

---------------------------------------------------------------------------------------------------------

首先:定義窗口實例和委托實例!對於 ArcObjects 來說屬性方法放在一個接口中,事件放在另外一個接口中!

ICustomizeDialog m_CustomizeDialog = new CustomizeDialogClass();     //自定義對話框實例
ICustomizeDialogEvents_OnStartDialogEventHandler startDialogE;           //開始對話框委托,通過事件可以找到需要事件的委托類型!
ICustomizeDialogEvents_OnCloseDialogEventHandler closeDialogE;    //關閉對話框委托

其次:定義函數!

private void OnStartDialogHandler()
{
    basicToolbarControl.Customize = true;       //工具條控件允許自定義工具
}
private void OnCloseDialogHandler()
{     
    basicToolbarControl.Customize = false;   //工具條控件不允許自定義工具
    chkCustomize.Checked = false;      //將復選框的√去掉
}

最后:實現事件!在 Form_Load 中寫的!

// Set the customize dialog box events.
ICustomizeDialogEvents_Event pCustomizeDialogEvent = m_CustomizeDialog as ICustomizeDialogEvents_Event;  //ICustomizeDialog 不具有事件,所以要查詢到有事件的接口
startDialogE = new ICustomizeDialogEvents_OnStartDialogEventHandler(OnStartDialogHandler);  //實例化開始委托
pCustomizeDialogEvent.OnStartDialog += startDialogE;  //用開始委托實現開始事件
closeDialogE = new ICustomizeDialogEvents_OnCloseDialogEventHandler(OnCloseDialogHandler);  //實例化關閉委托
pCustomizeDialogEvent.OnCloseDialog += closeDialogE;  //用關閉委托實現關閉事件
// Set the title.
m_CustomizeDialog.DialogTitle = "定制工具條";  //標題!
// Set the ToolbarControl that new items will be added to.
m_CustomizeDialog.SetDoubleClickDestination(basicToolbarControl);  //雙擊工具加到工具條控件中!

另外是與復選框的交互!

private void chkCustomize_CheckedChanged(object sender, EventArgs e)
{
    if (chkCustomize.Checked == false)
    {
        m_CustomizeDialog.CloseDialog();  //關閉自定義對話框
    }
    else
    {
        m_CustomizeDialog.StartDialog(basicToolbarControl.hWnd);  //彈出自定義對話框
    }
}

-------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第U1個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:Map 與 PageLayout 切換后工具不變

實現在切換前后,對於Map的工具恢復到之前的工具,而PageLayoutControl也是一樣的!

ITool pMapTool = null;  //定義存儲map的工具
ITool pPageLayoutTool = null;  //定義存儲pagelayout的工具
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (tabControl1.SelectedIndex == 0)
    {
        if (axPageLayoutControl1.CurrentTool != null)  //如果有工具則賦值,在沒有轉換buddy之前
            pPageLayoutTool = axPageLayoutControl1.CurrentTool;

        axToolbarControl1.SetBuddyControl(axMapControl1);

        if (axMapControl1.CurrentTool == null)  //理論上講默認都是null,然后給其賦值剛才的工具!
            axMapControl1.CurrentTool = pMapTool;
    }
    else
    {
        if (axMapControl1.CurrentTool != null)
            pMapTool = axMapControl1.CurrentTool;

        axToolbarControl1.SetBuddyControl(axPageLayoutControl1);

        if (axPageLayoutControl1.CurrentTool == null)
            axPageLayoutControl1.CurrentTool = pPageLayoutTool;
    }
}

-------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第U2個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:在窗體中顯示漸變顏色 & 通過名稱找控件

 實現效果:

實現代碼如下:

private void button1_Click(object sender, EventArgs e)
{
    IAlgorithmicColorRamp algColorRamp = new AlgorithmicColorRampClass();
    IRgbColor startColor = new RgbColor();
    startColor.Red = 255;
    IRgbColor endColor = new RgbColor();
    endColor.Green = 255;

    algColorRamp.FromColor = startColor;
    algColorRamp.ToColor = endColor;
    algColorRamp.Algorithm = esriColorRampAlgorithm.esriCIELabAlgorithm;
    algColorRamp.Size = 32;

    bool bture = true;
    algColorRamp.CreateRamp(out bture);

    IEnumColors pEnumColors = algColorRamp.Colors;

    for (int i = 1; i <= 32;i++ )
    {
        object o;
        PictureBox pb;
        o=this.GetType().GetField("pictureBox" + i.ToString(), 
            BindingFlags.Instance | BindingFlags.NonPublic).GetValue(this);  //通過控件名稱來找控件的方法
if (o != null)
        {
            pb = (PictureBox)o;
            pb.BackColor = ColorTranslator.FromOle(pEnumColors.Next().RGB);
        }
    }
}

自己定義 pictureBox,實現如下:

for (int i = 1; i <= 50;i++ )
{
    PictureBox pb = new PictureBox();
    pb.Height = 10;
    pb.Width = 500;
    pb.Location = new System.Drawing.Point(10, i * 12);
    panel1.Controls.Add(pb);
    pb.BackColor = ColorTranslator.FromOle(pEnumColors.Next().RGB);
}

-------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第U3個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:獲取地圖是否處於編輯狀態

引言:在操作地圖的時候,可能某人設置了,左鍵可以實現拉框放大,中鍵和右鍵怎可以實現漫游,但是若是這樣設置,當圖層處於編輯狀態的時候就糟糕了!因為操作會重疊,這個時候就需要判斷圖層是否處於編輯狀態,只有處於非編輯狀態的時候才要執行上面的方法!

IFeatureLayer pFeatureLayer = axMapControl1.Map.get_Layer(0) as IFeatureLayer;  //獲取 IFeatureLayer
IDataset pDataset =(IDataset) pFeatureLayer.FeatureClass;          //獲取 IDataset
IWorkspaceEdit pWorkspaceEdit = (IWorkspaceEdit) pDataset.Workspace;  //獲取 IWorkspaceEdit
if (pWorkspaceEdit.IsBeingEdited())
{
  //可以編輯狀態
}

●·● IDataset 接口

 

●·● IWorkspaceEdit 接口

-------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第U4個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:為某一要素添加字段內容

為要素添加字段內容,主要是用到了 set_Value 方法!然后記得用下 Store 方法!

string str001 = ((sender as Button).FindForm() as CheckForm).comboBox1.Text;
//Type字段內容
int int001 = Convert.ToInt32(((sender as Button).FindForm() as CheckForm).tb_Water_Quality.Text);
//Water_Quality字段內容
pDrawFeature.set_Value(pDrawFeature.Fields.FindField("Type"), str001);
pDrawFeature.set_Value(pDrawFeature.Fields.FindField("Water"), int001);
pDrawFeature.Store();       //存儲字段內容

-------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第U5個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:獲取地圖是否處於編輯狀態

引言:在操作地圖的時候,可能某人設置了,左鍵可以實現拉框 

-------------------------------------------------------------------------------------------------------

            ╔════════╗
╠════╣    第U6個    ╠══════════════════════════════════════════════════╣
            ╚════════╝

●·● 實現:獲取地圖是否處於編輯狀態

引言:在操作地圖的時候,可能某人設置了,左鍵可以實現拉框

 

 

 

 

 

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM