Arcengine 二次开发添加右键菜单

时间:2021-09-11 19:20:37

最近在搞arcengine 二次开发,遇到了好多问题,也通过网上查资料试着慢慢解决了,把解决的步骤记录下来,有需要帮助的可以看一下,也欢迎各位来批评指正。

想给自己的map application在图层上添加右键菜单,谷歌了一下,找到了解决的方法,原文的地址edndoc.esri.com/arcobjects/9.2/NET/1ED14BF2-A0E3-4e56-A70D-B9A7F7EC7880.htm。然后我根据这个添加了自己的右键菜单,又有一些改动。

效果如图所示(有点简陋)Arcengine 二次开发添加右键菜单,仅仅是简单的实现了一个删除当前图层的功能

首先添加成员变量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),在我添加了一个判断语句之后就没有问题了。

以上就是全部步骤啦。欢迎批评指正