最近在搞arcengine 二次開發,遇到了好多問題,也通過網上查資料試着慢慢解決了,把解決的步驟記錄下來,有需要幫助的可以看一下,也歡迎各位來批評指正。
想給自己的map application在圖層上添加右鍵菜單,谷歌了一下,找到了解決的方法,原文的地址edndoc.esri.com/arcobjects/9.2/NET/1ED14BF2-A0E3-4e56-A70D-B9A7F7EC7880.htm。然后我根據這個添加了自己的右鍵菜單,又有一些改動。
效果如圖所示(有點簡陋)
,僅僅是簡單的實現了一個刪除當前圖層的功能
首先添加成員變量IToolBarMenu,然后新建一個RemoveLayer類,基類是BaseCommand,RemoveLayer的代碼如下所示
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
namespace InstanceCluter.ContextMenu
{
public sealed class RemoveLayer : BaseCommand
{
private IMapControl3 m_mapControl;
public RemoveLayer()
{
base.m_caption = "刪除";
}
public override void OnClick()
{
//插入你自己的代碼
}
public override void OnCreate(object hook)
{
m_mapControl = (IMapControl3)hook;
}
}
}
你需要做的事在重寫OnClick函數,在里面實現你自己想要實現的功能,然后將自己實現的功能添加到右鍵菜單上去,代碼如下
private void CreateContextMenu()
{
m_menuLayer = new ToolbarMenuClass();
m_menuLayer.AddItem(new RemoveLayer(), -1, 0, false, esriCommandStyles.esriCommandStyleTextOnly);
m_menuLayer.SetHook(m_mapControl);
}
關於ToolbarMenuClass的使用可以去查官方文檔,接着將這個函數添加到MainForm_Load函數中去,然后給axTOCControl控件添加鼠標點擊事件(OnMouseDown),添加代碼如下
private void axTOCControl1_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e)
{
if (e.button != 2) return;
esriTOCControlItem item = esriTOCControlItem.esriTOCControlItemNone;
IBasicMap map = null; ILayer layer = null;
object other = null; object index = null;
//Determine what kind of item is selected
this.axTOCControl1.HitTest(e.x, e.y, ref item, ref map, ref layer, ref other, ref index);
//Ensure the item gets selected
if (item == esriTOCControlItem.esriTOCControlItemMap)
this.axTOCControl1.SelectItem(map, null);
//這里就是我和官方實例代碼不同的地方
else if (item == esriTOCControlItem.esriTOCControlItemLayer)
this.axTOCControl1.SelectItem(layer, null);
//Set the layer into the CustomProperty (this is used by the custom layer commands)
m_mapControl.CustomProperty = layer;
//Popup the correct context menu
if (item == esriTOCControlItem.esriTOCControlItemMap)
{
//用過arcgis,都知道這個layers的意思
MessageBox.Show("點擊了Layers");
}
if (item == esriTOCControlItem.esriTOCControlItemLayer)
{
m_menuLayer.PopupMenu(e.x, e.y, this.axTOCControl1.hWnd);
}
}
官方代碼和我的不同在於他直接用else,並沒有判斷item的類型,這樣的話,如果你在axTOCControl點擊的話,也執行該語句this.axTOCControl1.SelectItem(layer, null);,這樣就會引發異常(A valid object is required for this property),在我添加了一個判斷語句之后就沒有問題了。
以上就是全部步驟啦。歡迎批評指正
