建立新專案
首先我們開啟一個新的專案,範本請選擇ArcGIS=>Extending ArcObjects,目前只支援到.NET Framework3.5,所以請選擇.NET Framework3.5不然會沒有範本可以選擇喔,今天我們要針對ArcMap做開發,所以請選擇ClassLibrary(ArcMap),輸入該專案的名稱,輸入完畢後請點確認按鈕開啟專案。
加入參考 點選確定後,將會跳出選擇參考的視窗,我們可以從Desktop ArcMap底下找尋所要使用的References,典擊兩下即會加入參考,選擇完畢後點選Finish
刪除Class1.cs檔案
因為預設會幫我們加入該檔案,但是我們用不著,所以我們就把它刪了吧!點擊右鍵即可刪除!
建立 command
在專案按右鍵選擇新增項目後,我們到ArcGIS的Extending ArcObjects選擇BaseCommand項目,並輸入該項目名稱,我們輸入ZoomToLayer.cs完畢後,請點擊新增按鈕
接下來會詢問該Coommand的類型,因為我們這次要用在ArcMap,所以就選他囉!
撰寫Code
建立完後,我們首先需要修改的就是該項目的相關屬性,類別,標題,訊息,提示資訊,該項目唯一名稱
base.m_category = "Eric"; //localizable text base.m_caption = "Zoom To Layer 標題"; //localizable text base.m_message = "Zoom To Layer 左下角的訊息"; //localizable text base.m_toolTip = "Zoom To Layer"; //localizable text base.m_name = "Eric_ZoomToLayer"; //unique id, non-localizable (e.g. "MyCategory_ArcMapCommand")接下來我們可以透過ArcGIS的小工具快速幫我們建立常用的程式碼,我們在codebehind上面點擊右鍵,選擇 ArcGIS Snippet Finder,並輸入Zoom關鍵字去搜尋,搜尋後選擇我們要用到的程式碼select Zoom to Active Layer in TOC.snippet
#region "Zoom to Active Layer in TOC"
///Zooms to the selected layer in the TOC associated with the active view. ///
///An IMxDocument interface
///
///
public void ZoomToActiveLayerInTOC(IMxDocument mxDocument)
{
if (mxDocument == null)
{
return;
}
IActiveView activeView = mxDocument.ActiveView;
// Get the TOC
IContentsView IContentsView = mxDocument.CurrentContentsView;
// Get the selected layer
System.Object selectedItem = IContentsView.SelectedItem;
if (!(selectedItem is ILayer))
{
return;
}
ILayer layer = selectedItem as ILayer;
// Zoom to the extent of the layer and refresh the map
activeView.Extent = layer.AreaOfInterest;
activeView.Refresh();
}
#endregion
#region "Get MxDocument from ArcMap"
///Get MxDocument from ArcMap.
///An IApplication interface that is the ArcMap application.
///An IMxDocument interface.
///
public IMxDocument GetMxDocumentFromArcMap(IApplication application)
{
if (application == null)
{
return null;
}
IDocument document = application.Document;
IMxDocument mxDocument = (IMxDocument)(document); // Explicit Cast
return mxDocument;
}
#endregion
最後在點擊事件中加入該段程式碼
////// ////// public override void OnClick() { IMxDocument mxDocument = GetMxDocumentFromArcMap(m_application); ZoomToActiveLayerInTOC(mxDocument); }