GIS二次开发经典代码
C# GIS二次开发代码1
ESRI.ArcGIS.Display.CancelTracker pCancel = new ESRI.ArcGIS.Display.CancelTracker(); mapGIS.ActiveView.Output(pExport.StartExporting(), (int)pScreenResolution, ref pExportFrame, mapGIS.ActiveView.Extent, pCancel); pExport.FinishExporting(); } catch //()Exception ex { } }
3. 地图的空间查询
添加一个窗体,Name 为 QueryFrm。
在该窗体中添加控件,具体添加控件如下 空间名 GroupBox(Panel) 5 个 RadioButton Name groupBox rdoNormol rdoLine rdoEnvo rdoCircle rdoPoly Button btnOK 备注 一个容器,可以自行选择 Text 属性为:默认状态 Text 属性为:线选查询 Text 属性为:框选查询 Text 属性为:圆选查询 Text 属性为:多边形查询 Text 属性为:确定
2. 地图保存
在 menu 中添加 File,在 File 的中添加 Export Data,Name 为 exportDataMenu, 为其添加单击事件,代码如下 private void exportDataMenu_Click(object sender, EventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); //设置可以保存的文件类型 sfd.Filter = "TIF FIles(*.TIF)|*.TIF|SVG FIles(*.SVG)|*.SVG|PNG FIles(*.PNG)|*.PNG|PDF FIles(*.PDF)|*.PDF|JPEG FIles(*.JPEG)|*.JPEG|GIF FIles(*.GIF)|*.GIF|EMF FIles(*.EMF)|*.EMF|BMP FIles(*.BMP)|*.BMP|AI FIles(*.AI)|*.AI"; //显示对话框 sfd.ShowDialog(); //判断路径为空,返回 if (sfd.FileName == null) return; //获取保存文件路径 string path = sfd.FileName; string pathExtention = System.IO.Path.GetExtension(path); try { ESRI.ArcGIS.Output.IExport pExport; pExport = (ESRI.ArcGIS.Output.IExport)new ESRI.ArcGIS.Output.ExportTIFF(); //根据文件拓展名选择保存的格式 switch (pathExtention) { case ".SVG": pExport = (ESRI.ArcGIS.Output.IExport)new ESRI.ArcGIS.Output.ExportSVG(); break; case ".PS": pExport = (ESRI.ArcGIS.Output.IExport)new ESRI.ArcGIS.Output.ExportPS(); break; case ".PNG": pExport = (ESRI.ArcGIS.Output.IExport)new ESRI.ArcGIS.Output.ExportPNG();
用C 实现混合使用MAPGIS的多种二次开发方式
图3 然后选择GisEdit Contrl控件并插入,如图4、图5所示。
图4
图5 调整对话框大小及GisEdit控件大小,添加几个功能按钮,如图6所示。 白色部分为GisEdit控件。
图6 用C++实现混合使用MAPGIS的多种二次开发方式(二) 为了操作GisEdit控件,在ClassWizard中,将GisEdit控件添加为成员变 量。变量名为m_MapGIS。如图7所示
图1 注册成功后,出现图2所示对话框:
图2 如果没成功的话,看看是否和MAPGIS的DLL文件放在同一目录下,因为 它还要依赖MAPGIS的DLL库。 然后用VC中的MFC AppWizard生成一个对话框架的应用程序。打开 所生成的对话框资源,在对话框资源上右击,并选择Insert ActiveX Control…菜单。如图3所示。
} 为了在视窗改变大小时,m_MapGIS控件也改变大小,为视类添加一个 WM_SIZE消息,在其生成的OnSize函数中添加如下代码。 void CMapView::OnSize(UINT nType, int cx, int cy) { CView::OnSize(nType, cx, cy); // TODO: Add your message handler code here m_MapGIS.MoveWindows(cx,cy);// GisEdit控件中新增的改变窗口大小 函数 } 在菜单资源中,修改“打开文件”项,改成“打开工程文件”;并将其(资 源ID号:ID_FILE_OPEN) 在视窗类中(本例为CMapView)建立消息 映射。在映射函数中加入如下代码: void CMapView::OnFileOpen() { // TODO: Add your command handler code here m_MapGIS.LoadProject(); } 编译整个工程并运行,打开一个MAPGIS工程文件,运行结果如图11, 所示
GIS二次开发—空间分析窗体代码
namespace MapAnalyse{public class Function{//打开通过属性查询地图窗口public static void SelectByAttribute(AxMapControl axMapControl){frmSelectByAttributes frmselectbyattrib = new frmSelectByAttributes(axMapControl);frmselectbyattrib.Show();}//打开通过位置查询地图窗口public static void SelectByLocation(AxMapControl axMapControl){frmSelectByLocation frmselectbylocation = new frmSelectByLocation(axMapControl);frmselectbylocation.Show();}//打开缓冲区分析窗口public static void BufferAnalyse(AxMapControl axMapControl){//frmBufferAnalyse frmbuffer = new frmBufferAnalyse(axMapControl);//frmbuffer.Show();frmBufferAnalyse frmbuffer = new frmBufferAnalyse(axMapControl);frmbuffer.Show();}//打开叠置分析窗口public static void OverLayerAnalyse(AxMapControl axMapControl){frmOverLayerAnalyse frmoverlayer = new frmOverLayerAnalyse(axMapControl);frmoverlayer.Show();}//打开网络分析窗口public static void NetAnalyse(AxMapControl axMapControl){frmNetAnalyse frmnetanalyse = new frmNetAnalyse(axMapControl);frmnetanalyse.Show();}//转换像素到地图单位public static double ConvertPixelsToMapUnits(IActiveView pActiveView, double pixelUnits){tagRECT pRect = pActiveView.ScreenDisplay.DisplayTransformation.get_DeviceFrame();int pixelExtent = pRect.right - pRect.left;double realWorldDisplayExtent =pActiveView.ScreenDisplay.DisplayTransformation.VisibleBounds.Width;double sizeOfOnePixel = realWorldDisplayExtent / pixelExtent;return pixelUnits * sizeOfOnePixel;}public static IFeatureLayer GetLayerByNameFromGroupLayer(string strLayerName, ILayer iLayer) {ILayer _iLayer = iLayer;ICompositeLayer pGroupLayer = _iLayer as ICompositeLayer;for (int j = 0; j < pGroupLayer.Count; j++){_iLayer = pGroupLayer.get_Layer(j) as IFeatureLayer;if (_iLayer is IGroupLayer){GetLayerByNameFromGroupLayer(strLayerName, _iLayer);}else if (_iLayer is IFeatureLayer){if (_ == strLayerName){return _iLayer as IFeatureLayer;}}}return null;}private static int count = 0;//在图层组中通过索引获得图层public static IFeatureLayer GetLayerNumFromGroupLayer(int index, ILayer iLayer) {ILayer _iLayer = iLayer;ICompositeLayer pGroupLayer = _iLayer as ICompositeLayer;for (int j = 0; j < pGroupLayer.Count; j++){_iLayer = pGroupLayer.get_Layer(j) as IFeatureLayer;if (_iLayer is IGroupLayer){IFeatureLayer pFeatLyr = GetLayerNumFromGroupLayer(index, _iLayer);if (pFeatLyr != null){return pFeatLyr;}}else if (_iLayer is IFeatureLayer){count++;if (count == index){return _iLayer as IFeatureLayer;}}}return null;}//通过索引获得图层public static IFeatureLayer GetLayerByIndex(int index, AxMapControl axMap){count = 0;IFeatureLayer pFeatLyr = null;if (yerCount > 0){for (int i = 0; i < yerCount; i++){ILayer _iLayer = axMap.Map.get_Layer(i);if (_iLayer is IGroupLayer){pFeatLyr = GetLayerNumFromGroupLayer(index, _iLayer);if (pFeatLyr != null){return pFeatLyr;}}else if (_iLayer is IFeatureLayer){count++;if (count == index){return _iLayer as IFeatureLayer;}}}}return pFeatLyr;}//通过名称获得图层public static IFeatureLayer GetLayerByName(string strLayerName, AxMapControl axMap) {IFeatureLayer pFeatLyr = null;if (yerCount > 0){for (int i = 0; i < yerCount; i++){ILayer _iLayer = axMap.Map.get_Layer(i);if (_iLayer is IGroupLayer){pFeatLyr = GetLayerByNameFromGroupLayer(strLayerName, _iLayer);if (pFeatLyr != null)return pFeatLyr;//ICompositeLayer pGroupLayer = _iLayer as ICompositeLayer;//for (int j = 0; j < pGroupLayer.Count; j++)//{// _iLayer = pGroupLayer.get_Layer(j) as IFeatureLayer;// if (_ == strLayerName)// {// pFeatLyr = _iLayer as IFeatureLayer;// }//}}else if (_iLayer is IFeatureLayer){if (_ == strLayerName){pFeatLyr = _iLayer as IFeatureLayer;return pFeatLyr;}}}}return pFeatLyr;}//得到地图中的指定特征图成指定字段的不重复值public static IEnumVariantSimple GetUniqueValue(string strFieldName, AxMapControl axMap, string strLayerName){IFeatureLayer pFeatLayer = GetLayerByName(strLayerName, axMap);ICursor pCursor = pFeatLayer.Search(null, false) as ICursor;IDataStatistics pDatasetStat = new DataStatisticsClass();pDatasetStat.Field = strFieldName;pDatasetStat.Cursor = pCursor;return pDatasetStat.UniqueValues as IEnumVariantSimple;}//颜色转换public static IRgbColor GetRGBColor(int red, int green, int blue){IRgbColor pColor = new RgbColorClass();pColor.Red = red;pColor.Green = green;pColor.Blue = blue;return pColor;}}public class BufferAnalyse{public void CreateGraphicBuffersAroundSelectedFeatures(ESRI.ArcGIS.Carto.IActiveView activeView, System.Double distance)//缓冲区分析?{if (activeView == null || distance < 0){return;}ESRI.ArcGIS.Carto.IMap map = activeView.FocusMap;ESRI.ArcGIS.Carto.IGraphicsContainer graphicsContainer =(ESRI.ArcGIS.Carto.IGraphicsContainer)map; // Explicit CastgraphicsContainer.DeleteAllElements();if (map.SelectionCount == 0){return;}ESRI.ArcGIS.Geodatabase.IEnumFeature enumFeature =(ESRI.ArcGIS.Geodatabase.IEnumFeature)map.FeatureSelection; // Explicit CastenumFeature.Reset();ESRI.ArcGIS.Geodatabase.IFeature feature = enumFeature.Next();ESRI.ArcGIS.Geometry.ITopologicalOperator topologicalOperator;ESRI.ArcGIS.Carto.IElement element;while (!(feature == null)){topologicalOperator = (ESRI.ArcGIS.Geometry.ITopologicalOperator)feature.Shape; // Explicit Castelement = new ESRI.ArcGIS.Carto.PolygonElementClass();element.Geometry = topologicalOperator.Buffer(distance);graphicsContainer.AddElement(element, 0);feature = enumFeature.Next();}activeView.PartialRefresh(ESRI.ArcGIS.Carto.esriViewDrawPhase.esriViewGraphics, null, null);}}private AxMapControl axMapControl1;private string m_OutputFilename;private string m_OutputPath;public frmOverLayerAnalyse(AxMapControl axMapControl){InitializeComponent();axMapControl1 = axMapControl;InitForm();}//初始化窗体数据private void InitForm(){this.cmb_OverLayMethod.SelectedIndex = 0;InitLayer();}//初始化地图图层private void InitLayer(){this.cmb_InputLayer1.Items.Clear();this.cmb_InputLayer2.Items.Clear();if (yerCount > 0){for (int i = 0; i < yerCount; i++){ILayer _iLayer = axMapControl1.Map.get_Layer(i);if (_iLayer is IGroupLayer){ICompositeLayer pGroupLayer = _iLayer as ICompositeLayer;for (int j = 0; j < pGroupLayer.Count; j++){_iLayer = pGroupLayer.get_Layer(j) as IFeatureLayer;cmb_InputLayer1.Items.Add(_);cmb_InputLayer2.Items.Add(_);}}else if (_iLayer is IFeatureLayer){//_iLayer = axMapControl1.Map.get_Layer(i) as IFeatureLayer;cmb_InputLayer1.Items.Add(_);cmb_InputLayer2.Items.Add(_);}}}else{MessageBox.Show("未找到地图图层");}}//获取生成图层路径和文件名private bool GainTheOutputPath(){string _file = this.txt_OutputLayerPath.Text;if (_file == ""){return false;}else{m_OutputFilename = _file.Split('\\')[_file.Split('\\').Length - 1];m_OutputPath = this.txt_OutputLayerPath.Text.Substring(0, _file.Length -m_OutputFilename.Length - 1);return true;}}private void btn_Apply_Click(object sender, EventArgs e){if (yerCount < 2){MessageBox.Show("添加至少两个图层后再做叠层分析", "提示");return;}if (this.cmb_InputLayer1.SelectedIndex == -1 || this.cmb_InputLayer2.SelectedIndex == -1){MessageBox.Show("请选择需要叠置分析的图层", "提示");return;}if (!GainTheOutputPath()){MessageBox.Show("请设置分析结果输出位置", "提示");return;}OverLayer();}private void OverLayer(){IFeatureLayer pInputFLayer;IFeatureLayer pOverlayFLayer;string strWorkspaceFactoryProgID;string strPathName;bool useSelectedInput;bool useSelectedOverlay;double dTolerance;useSelectedInput = false;useSelectedOverlay = false;//pInputFLayer = axMapControl1.get_Layer(4) as IFeatureLayer;//pOverlayFLayer = axMapControl1.get_Layer(5) as IFeatureLayer;//选?中D图ª?层?1string _layer = cmb_InputLayer1.SelectedItem.ToString();pInputFLayer = Function.GetLayerByName(_layer, axMapControl1);//选?中D图ª?层?2string _layer2 = cmb_InputLayer2.SelectedItem.ToString();pOverlayFLayer = Function.GetLayerByName(_layer2, axMapControl1);dTolerance = 0.01;strWorkspaceFactoryProgID = "esriDataSourcesFile.ShapefileWorkspaceFactory.1";//strPathName = @"D:\Download\_AEtemp\overlay";strPathName = m_OutputPath;ITable pInputTable = GetFeatureLayerTable(pInputFLayer, false);if (pInputTable == null)return;ITable pOverlayTable = GetFeatureLayerTable(pOverlayFLayer, false);if (pOverlayTable == null)return;//创建输出要素类的名称指定输出位置IFeatureClassName pFCName = new FeatureClassNameClass();IWorkspaceName pWSName = new WorkspaceNameClass();pWSName.WorkspaceFactoryProgID = strWorkspaceFactoryProgID;pWSName.PathName = strPathName;IDatasetName pDatasetName = (IDatasetName)pFCName;// = "Intersect_result"; = m_OutputFilename.Substring(0, m_OutputFilename.Length - 4);pDatasetName.WorkspaceName = pWSName;//执行叠置IBasicGeoprocessor pBGP = new BasicGeoprocessorClass();IFeatureClass pOutFClass = null;try{switch (this.cmb_OverLayMethod.SelectedIndex){case 0: //Union 分割组合pOutFClass = pBGP.Union(pInputTable, useSelectedInput, pOverlayTable, useSelectedOverlay, dTolerance, pFCName);break;case 1: //Intersect 相交pOutFClass = pBGP.Intersect(pInputTable, useSelectedInput, pOverlayTable, useSelectedOverlay, dTolerance, pFCName);break;case 2: //SpatialJoin{Geoprocessor gp = new Geoprocessor();gp.OverwriteOutput = true;SpatialJoin pSJ = new SpatialJoin(pInputFLayer, pOverlayFLayer,m_OutputPath + "\\" + m_OutputFilename);pSJ.join_operation = "JOIN_ONE_TO_ONE";//gp.Execute(pSJ, null);pOutFClass = pSJ.out_feature_class as IFeatureClass;IGeoProcessorResult igpr = gp.Execute(pSJ, null) as IGeoProcessorResult;if (igpr == null){string strerror = "";for (int i = 0; i < gp.MessageCount; i++){strerror = strerror + "\n" + gp.GetMessage(i);}MessageBox.Show("未成功\n" + strerror, "出错了?");return;}}break;case 3: //Erase擦除{Geoprocessor gp = new Geoprocessor();gp.OverwriteOutput = true;Erase erase = new Erase(pInputFLayer, pOverlayFLayer, m_OutputPath + "\\" + m_OutputFilename);gp.Execute(erase, null);IGeoProcessorResult igpr = gp.Execute(erase, null) as IGeoProcessorResult;if (igpr == null){string strerror = "";for (int i = 0; i < gp.MessageCount; i++){strerror = strerror + "\n" + gp.GetMessage(i);}MessageBox.Show("未成功,错误信息如下? \n" + strerror, "出错了?");return;}}break;}//Add the output layer to the mapif (this.cb_AddOutputLayerToCurMap.Checked == true){IFeatureLayer pOutputFLayer;pOutputFLayer = new FeatureLayerClass();pOutputFLayer.FeatureClass = pOutFClass; = pOutFClass.AliasName;axMapControl1.AddLayer(pOutputFLayer);}MessageBox.Show("通过" + this.cmb_OverLayMethod.SelectedItem + " 方法叠置分析生成的图层保存在\n" + m_OutputPath + "\\" + m_OutputFilename, "分析成功!");}catch (Exception ex){MessageBox.Show(ex.ToString(), "叠置求交失败");return;}if (pOutFClass == null)return;//axMapControl1.AddLayer(pOutFClass);/*//返回叠置求交结果?IFeatureLayer pOutputFLayer = new FeatureLayerClass();pOutputFLayer.FeatureClass = pOutFClass;string strFCAliasName = pOutFClass.AliasName; = strFCAliasName;return pOutputFLayer;*/}private ITable GetFeatureLayerTable(IFeatureLayer pFLayer, bool IsUnion){if (pFLayer == null)return null;IFeatureClass pFC = pFLayer.FeatureClass;if (IsUnion == true && pFC.ShapeType != esriGeometryType.esriGeometryPolygon){MessageBox.Show("图层的类型必须是面图层请重新设置?");return null;}ITable pTable = (ITable)pFLayer;return pTable;}private void btn_OutputLayer_Click(object sender, EventArgs e){//set the output layerSaveFileDialog saveDlg = new SaveFileDialog();saveDlg.CheckPathExists = true;saveDlg.Filter = "Shapefile (*.shp)|*.shp";saveDlg.OverwritePrompt = true;saveDlg.Title = "Output Layer";saveDlg.RestoreDirectory = true;saveDlg.FileName = (string)this.cmb_InputLayer1.SelectedItem + "_" +this.cmb_OverLayMethod.SelectedItem + ".shp";DialogResult dr = saveDlg.ShowDialog();if (dr == DialogResult.OK)this.txt_OutputLayerPath.Text = saveDlg.FileName;}private void btn_Calcel_Click(object sender, EventArgs e){this.Close();}}。
arcgis二次开发算法
arcgis二次开发算法
以下是一个基本的 ArcGIS 二次开发算法,该算法演示了如何使用 C 和ArcGIS Engine 创建和运行一个自定义的地图算法:
```csharp
using System;
using ;
using ;
using ;
using ;
public class MyMapAlgorithm :
{
protected override void CreateMap( mapDocument)
{
// 创建一个新的图层,并设置其数据源
layer = (new ());
= "My Layer";
= "C:\Data\";
// 创建一些新的空间查询条件,以选择地图上的特定区域
spatialFilter = new ();
= ; // 仅选择整个地图区域
= ;
// 应用空间过滤器到图层,并执行空间查询以获取满足条件的要素
(spatialFilter);
}
}
```
在这个示例中,我们创建了一个名为“MyMapAlgorithm”的自定义地图
算法,它继承自类。
在CreateMap 方法中,我们首先创建一个新的图层,并设置其数据源为一个 Shapefile 文件。
然后,我们创建一个空间过滤器,用于选择地图上的特定区域。
最后,我们将空间过滤器应用到图层上,并执行空间查询以获取满足条件的要素。
arcgis二次开发符号化代码
在ArcGIS 中,符号化是通过改变图形的颜色,线宽,类型等属性来使地图更具视觉效果的过程。
下面是一个基本的ArcGIS 二次开发符号化代码的示例,它使用了C# 和ArcObjects。
csharp复制代码using ESRI.ArcGIS.Carto;using ESRI.ArcGIS.Geodatabase;using ESRI.ArcGIS.DataSourcesFile;public void SymbolizeFeatureLayer(ILayer layer, stringlayerFilePath){// 创建图层工厂ILayerFile layerFile = new LayerFileClass();// 打开指定的图层文件if (layerFile.IsLayerFile[layerFilePath]){layerFile.Open(layerFilePath);// 获取图层ILayer layerTemp = yer;// 符号化图层SymbolLayerList symbolLayers = layerTemp.SymbologyType asSymbolLayerList;if (symbolLayers != null){for (int i = 0; i < symbolLayers.Count; i++){ISymbolLayer symbolLayer = symbolLayers[i];symbolLayer.Symbol.Color = new RgbColorClass(255, 0, 0); // 设置颜色为红色symbolLayer.Symbol.OutlineColor = new RgbColorClass(0, 0, 0); // 设置轮廓颜色为黑色}}// 刷新图层以应用更改layer.Refresh();}}在这个例子中,我们首先打开一个指定的图层文件,然后遍历该图层的所有符号图层。
C# GIS二次开发代码4
备注 容器 Text:图层 Text:缓冲区距离
输出图层 Text:… Text:信息提示 Multiline 设为 True Text:建立缓冲区 Text:.Geoprocessor ESRI.ArcGIS.AnalysisTools ESRI.ArcGIS.Geoprocessing 添加命名空间 using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.Carto; using System.Runtime.InteropServices; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geoprocessor; using ESRI.ArcGIS.AnalysisTools; using ESRI.ArcGIS.Geoprocessing; 在 Buffer 类下添加如下代码: [DllImport("user32.dll")] private static extern int PostMessage(IntPtr wnd, uint Msg, IntPtr wParam, IntPtr iParam); private IHookHelper m_hookHelper = null; private const uint WM_VSCROLL = 0x115; private const uint SB_BOTTOM = 7; 修改默认的构造函数,通过构造函数传值 public Buffer(IHookHelper hookHelper) { InitializeComponent(); m_hookHelper = hookHelper; }
private void btnBuffer_Click(object sender, EventArgs e) { double bufferDistance; double.TryParse(txtBufferDistance.Text, out bufferDistance); if (bufferDistance == 0.0) { MessageBox.Show("不适当的缓冲区距离"); return; } if ((!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(txtOutputPath.Text ))) || ".shp" != System.IO.Path.GetExtension(txtOutputPath.Text)) { MessageBox.Show("无效的输出文件名!"); return; } if (m_yerCount == 0) return; IFeatureLayer layer=GetFeatureLayer((string)cboLayers.SelectedItem); if (layer == null) { txtMessage.Text = "图层" + (string)cboLayers.SelectedItem + " 无法找到\r\n"; return; } ScrollToBottom(); txtMessage.Text = "缓冲区图层:"++"\r\n"; txtMessage.Text += "\r\n正在处理中.这需要几秒钟时间...\r\n"; txtMessage.Update(); Geoprocessor gp = new Geoprocessor(); gp.OverwriteOutput=true; txtMessage.Text += "正在建立缓冲区...\r\n"; txtMessage.Update(); ESRI.ArcGIS.AnalysisTools.Buffer buffer=new ESRI.ArcGIS.AnalysisTools.Buffer(layer,txtOutputPath.Text,Convert.ToString(buffe rDistance)+" "+(string)cboUnits.SelectedItem);
C# GIS二次开发代码6
mapGIS.Visible = false;
layoutMain.Visible = true; toolGIS.SetBuddyControl(layoutMain); dataViewMenu.Checked = false; layoutViewMenu.Checked = true; CopyMapFromMaptoPageLayout();
} catch (Exception) {
} }Leabharlann mapGIS.Visible = true; toolGIS.SetBuddyControl(mapGIS); layoutMain.Visible = false; dataViewMenu.Checked = true; layoutViewMenu.Checked = false;
} layoutViewMenu 的单击事件: private void layoutViewMenu_Click(object sender, EventArgs e) {
layoutMain.Left = mapGIS.Left; layoutMain.Top = mapGIS.Top; layoutMain.Width = mapGIS.Width; layoutMain.Height = mapGIS.Height;
给 dataViewMenu 添加单击事件 在此事件中,改变 mapGIS 和 layoutMain 的 visible,并在菜单上选中相应的菜单。并设置与 toolGIS 关联的控件。 private void dataViewMenu_Click(object sender, EventArgs e) {
pFileName.Path = pFillePaths[i]; CreateLayer((IName)pFileName); } } } else if (pDadaObject.CanGetNames()) { pEnumName = pDadaObject.GetNames(); pEnumName.Reset(); pName = pEnumName.Next(); do { CreateLayer(pName); pName = pEnumName.Next(); } while (pName!=null); } } } public void CreateLayer(IName pName) { try { mapGIS.MousePointer = esriControlsMousePointer.esriPointerHourglass; ILayerFactoryHelper pLayerFactoryHelper; pLayerFactoryHelper = new LayerFactoryHelperClass(); IEnumLayer pEnumLayer; pEnumLayer = pLayerFactoryHelper.CreateLayersFromName(pName); pEnumLayer.Reset(); ILayer pLayer; pLayer = pEnumLayer.Next(); do { mapGIS.AddLayer(pLayer); pLayer = pEnumLayer.Next(); } while (pLayer!=null); mapGIS.MousePointer = esriControlsMousePointer.esriPointerDefault;
优-ArcGIS Engine 的一些实现代码C#二次开发ArcGis
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); //在新定义图层的基础上进行的查询
●·● 实现:只显示筛选的要素:
--------------------------------------------------------------------------------------------------------
●·● IFeatureLayerDefinition 接口:
●·● 实现:鼠标滑过显示要素 tip:
对于这个有两个方法: 第一种:通过将 axmapcontrol 自带的 ShowMapTips 属性设置为 true 来实现。 第二种:通过 .NET 自带的控件 ToolTip 来实现! 第一种代码:
GIS二次开发实验指导书(实验5)
实验五PageLayout属性设置与元素绘制1、新建项目,设置窗体界面如下:2、在主窗体的Load事件中添加如下代码:private void FormMain_Load(object sender, EventArgs e){Microsoft.Win32.RegistryKey pRegKey =Microsoft.Win32.Registry.LocalMachine.OpenSubKey("SOFTWARE\\ESRI\\CoreRuntime", true);axSymbologyControl1.LoadStyleFile(pRegKey.GetValue("InstallDir") +"\\Styles\\ESRI.ServerStyle");axSymbologyControl1.GetStyleClass(esriSymbologyStyleClass.esriStyleClassBackgrounds).Update ();axSymbologyControl1.GetStyleClass(esriSymbologyStyleClass.esriStyleClassBorders).Update();axSymbologyControl1.GetStyleClass(esriSymbologyStyleClass.esriStyleClassShadows).Update(); }3、在“设置边框”按钮的Click事件中添加如下代码:private void ButtonBorder_Click(object sender, EventArgs e){axSymbologyControl1.StyleClass = esriSymbologyStyleClass.esriStyleClassBorders; }4、在“设置阴影”按钮的Click事件中添加如下代码:private void ButtonShadows_Click(object sender, EventArgs e){axSymbologyControl1.StyleClass = esriSymbologyStyleClass.esriStyleClassShadows; }5、在“设置背景”按钮的Click事件中添加如下代码:private void ButtonBackground_Click(object sender, EventArgs e){axSymbologyControl1.StyleClass =esriSymbologyStyleClass.esriStyleClassBackgrounds;}6、在axSymbologyControl1控件的OnItemSelected事件中添加如下代码:private void axSymbologyControl1_OnItemSelected(object sender, ISymbologyControlEvents_OnItemSelectedEvent e){IStyleGalleryItem pStyleGalleryItem = e.styleGalleryItem as IStyleGalleryItem;IFrameProperties pFrameProperties =axPageLayoutControl1.GraphicsContainer.FindFrame(axPageLayoutControl1.ActiveView.FocusMap) as IFrameProperties;if (pStyleGalleryItem.Item is IBackground){pFrameProperties.Background = pStyleGalleryItem.Item as IBackground;}else if (pStyleGalleryItem.Item is IBorder){pFrameProperties.Border = pStyleGalleryItem.Item as IBorder;}else if (pStyleGalleryItem.Item is IShadow){pFrameProperties.Shadow = pStyleGalleryItem.Item as IShadow;}axPageLayoutControl1.Refresh(esriViewDrawPhase.esriViewBackground, null, null); }7、在“设置网格”按钮的Click事件中添加如下代码:private void ButtonGrid_Click(object sender, EventArgs e){IActiveView pActiveView = axPageLayoutControl1.PageLayout as IActiveView;IMap pMap = pActiveView.FocusMap;IMeasuredGrid pMeasuredGrid = new MeasuredGridClass();IMapGrid pMapGrid = pMeasuredGrid as IMapGrid;pMeasuredGrid.FixedOrigin = true;pMeasuredGrid.Units = pMap.MapUnits;pMeasuredGrid.XIntervalSize = 10;pMeasuredGrid.YIntervalSize = 10;pMeasuredGrid.XOrigin = -180;pMeasuredGrid.YOrigin = -90;IProjectedGrid pProjectedGrid = pMeasuredGrid as IProjectedGrid;pProjectedGrid.SpatialReference = pMap.SpatialReference; = "Measured Grid";IGraphicsContainer pGraphicsContainer = pActiveView as IGraphicsContainer;IMapFrame pMapFrame = pGraphicsContainer.FindFrame(pMap) as IMapFrame;IMapGrids pMapGrids = pMapFrame as IMapGrids;pMapGrids.AddMapGrid(pMapGrid);pActiveView.PartialRefresh(esriViewDrawPhase.esriViewBackground, null, null); }8、程序运行最终界面如下:思考题:1、IStyleGalleryItem接口有哪些属性,各属性有何作用?2、叙述实现“设置网格”功能的编程思路。
ArcGIS二次开发测量功能
ArcGIS二次开发之实现测量功能ArcGIS二次开发之实现测量功能,源代码如下:copyright dedecmspublic override void OnMouseDown(int Button, int Shift, int X, int Y) {// TODO: Add Tool2.OnMouseDown implementationm_bInUse = true;m_pStartPoint =m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);}public override void OnMouseMove(int Button, int Shift, int X, int Y){// TODO: Add Tool2.OnMouseMove implementationbFirstTime = false;IPoint pPoint;IRgbColor pRGBColor;ILine pLine;ISymbol pSymbol = null;double dAngle;double dDeltaX;double dDeltaY;double dDistance;IPolyline pPolyline;ISegmentCollection pSegmentCollection;内容来自dedecmsif (m_pLinePolyline == null){bFirstTime = true;}pPoint = m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);m_hookHelper.ActiveView.ScreenDisplay.StartDrawing(m_hookHelper.ActiveView.ScreenDis play.hDC, -1);if (bFirstTime){m_pLineSymbol = new SimpleLineSymbolClass();m_pLineSymbol.Width = 1;pRGBColor = new RgbColorClass();pRGBColor.Red = 222;pRGBColor.Green = 222;pRGBColor.Blue = 222;m_pLineSymbol.Color = pRGBColor;pSymbol = m_pLineSymbol as ISymbol;pSymbol.ROP2 = esriRasterOpCode.esriROPXOrPen;m_pTextSymbol = new TextSymbolClass();织梦好,好织梦m_pTextSymbol.HorizontalAlignment = esriTextHorizontalAlignment.esriTHACenter;m_pTextSymbol.VerticalAlignment = esriTextVerticalAlignment.esriTVACenter;m_pTextSymbol.Size = 10;pSymbol = m_pTextSymbol as ISymbol;System.Drawing.Font pFont = new System.Drawing.Font("Arial", 10, FontStyle.Bold);m_pTextSymbol.Font = (stdole.IFontDisp)OLE.GetIFontDispFromFont(pFont);pSymbol.ROP2 = esriRasterOpCode.esriROPXOrPen;copyright dedecmsm_pTextPoint = new PointClass();}else{m_hookHelper.ActiveView.ScreenDisplay.SetSymbol((ISymbol)m_pTextSymbol);m_hookHelper.ActiveView.ScreenDisplay.DrawText(m_pTextPoint, m_pTextSymbol.Text);m_hookHelper.ActiveView.ScreenDisplay.SetSymbol((ISymbol)m_pLineSymbol);if (m_pLinePolyline.Length > 0){m_hookHelper.ActiveView.ScreenDisplay.DrawPolyline(m_pLinePolyline);}}pLine = new LineClass();pLine.PutCoords(m_pStartPoint, pPoint);dAngle = pLine.Angle;dAngle = dAngle * (180.0 / 3.14159);if ((dAngle > 90.0) && (dAngle < 180.0))dAngle = dAngle + 180.0;else if ((dAngle < 0.0) && (dAngle > -90.0))dAngle = dAngle - 180.0;else if ((dAngle < -90.0) && (dAngle > -180.0))dAngle = dAngle - 180.0;else if (dAngle > 180)dAngle = dAngle - 180;织梦好,好织梦dDeltaX = pPoint.X - m_pStartPoint.X;dDeltaY = pPoint.Y - m_pStartPoint.Y;m_pTextPoint.X = m_pStartPoint.X + dDeltaX / 2.0;m_pTextPoint.Y = m_pStartPoint.Y + dDeltaY / 2.0;m_pTextSymbol.Angle = dAngle;dDistance = System.Math.Round(pLine.Length, 3);m_pTextSymbol.Text = "[" + dDistance + "]";m_hookHelper.ActiveView.ScreenDisplay.SetSymbol((ISymbol)m_pTextSymbol);m_hookHelper.ActiveView.ScreenDisplay.DrawText(m_pTextPoint, m_pTextSymbol.Text);织梦内容管理系统object o=Type.Missing;pPolyline = new PolylineClass();pSegmentCollection = pPolyline as ISegmentCollection;pSegmentCollection.AddSegment((ISegment)pLine, ref o, ref o);m_pLinePolyline = GetSmashedLine(m_hookHelper.ActiveView.ScreenDisplay, (ISymbol)m_pTextSymbol, m_pTextPoint, pPolyline);m_hookHelper.ActiveView.ScreenDisplay.SetSymbol((ISymbol)m_pLineSymbol);if (m_pLinePolyline.Length > 0)m_hookHelper.ActiveView.ScreenDisplay.DrawPolyline(m_pLinePolyline);m_hookHelper.ActiveView.ScreenDisplay.FinishDrawing();}public override void OnMouseUp(int Button, int Shift, int X, int Y){// TODO: Add Tool2.OnMouseUp implementationm_bInUse = false;m_hookHelper.ActiveView.ScreenDisplay.StartDrawing(m_hookHelper.ActiveView.ScreenDis play.hDC, -1);m_hookHelper.ActiveView.ScreenDisplay.SetSymbol((ISymbol)m_pTextSymbol);m_hookHelper.ActiveView.ScreenDisplay.DrawText(m_pTextPoint, m_pTextSymbol.Text);m_hookHelper.ActiveView.ScreenDisplay.SetSymbol((ISymbol)m_pLineSymbol);if (m_pLinePolyline.Length > 0)m_hookHelper.ActiveView.ScreenDisplay.DrawPolyline(m_pLinePolyline);织梦内容管理系统m_hookHelper.ActiveView.ScreenDisplay.FinishDrawing();}public override bool Deactivate(){m_pTextSymbol = null;m_pTextPoint = null;m_pLinePolyline = null;m_pLineSymbol = null;m_bInUse = false;return true;}private IPolyline GetSmashedLine(IScreenDisplay pDisplay, ISymbol pTextSymbol, IPoint pPoint, IPolyline pPolyline){IPolygon pBoundary;ITopologicalOperator pTopologicalOperator;IPolyline pIntersect;本文来自织梦pBoundary=new PolygonClass();pTextSymbol.QueryBoundary(pDisplay.hDC,pDisplay.DisplayTransformation,pPoint,pBoundar y);pTopologicalOperator=pBoundary as ITopologicalOperator;pIntersect = pTopologicalOperator.Intersect(pPolyline,esriGeometryDimension.esriGeometry1Dimension) as IPolyline;pTopologicalOperator = pPolyline as ITopologicalOperator;return pTopologicalOperator.Difference(pIntersect) as IPolyline;}public override void OnDblClick(){m_hookHelper.ActiveView.Refresh();}#endregion}距离的测量:要实现的是测量两个点之间的距离。
Mapgis二次开发(入门)
Mapgis二次开发(入门)——MFC下的基本步骤作者:刘明瓒成都理工大学QQ:34194203欢迎大家转载此文,但请在转载时保证文章的完整性开发平台:VC++6.0&&Mapgis6.75内容:mapgis二次开发的一些基本概念和基本步骤要求:阅读此文需要一定C++编程基础和一点MFC的知识以及一点mapgis知识。
1概述1.1Mapgis二次开发的作用扩展mapgis产品功能,以达到自己的目的。
简单讲有:简化操作(将mapgis产品提供的功能包装,以前要点几下的现在点一下就可以了),功能扩展(mapgis产品没有的功能,可以通过二次开发自己实现),功能应用(自己开发的某个系统如果想使用mapgis里面的一些功能,可以通过二次开发直接拿到自己的系统中),……等等。
1.2基本概念有一点需要说明,mapgis二次开发所有API函数都是以“_”开头的,如_OpenPntArea、_GetPnt、_GetLin等等。
其他概念在要碰到时在谈。
1.3所需工具1、Microsoft Studio VC++6.02、Mapgis6.75产品及二次开发包以上工具网上均有免费下载, 进行一下步骤时请先下载并安装好。
2Mfc向导与工程设置2.1新建工程(1)打开VC++6.0 【File】->【New】选择【Projects】选项卡、【MFC AppWizard(exe)】、填入工程名称Mapgis_1,点击【OK】如下图:(2)选择Dialog based (为简单起见)点击【Finish】新建工程完毕2.2工程设置(1)点击菜单栏【Project】->【Setting】选择【C/C++】选项卡 Category:中选择【Code Generation】Struct member alignment选择【1 Byte】点击【OK】说明:此步设置是将C++结构体成员的内存对齐方式设置为1字节,因为mapgis6.X的开发就是采用的此对齐方式。
ArcGISEngine二次开发——提高篇
.ArcGIS Engine二次开发——提高篇1缩略图(鹰眼)鹰眼功能是GIS的主要功能之一,当地图范围很大时,它可以很好的为用户指明当前地图的范围。
在本小节中我们将学习如何制作这种鹰眼。
1.1添加控件新建一个C#.Net项目,项目名称为OverView,将Form1的名字设置为MainForm,并添加ToolbarControl 、两个MapControl和LicenceControl等四个控件。
布局如下图所示。
左边的axMapControl1用于地图数据显示和操作,右边axMapControl2用于鹰眼显示。
图 1 界面布局在ToolbarControl 加载添加数据按钮和地图浏览的功能按钮,如下图所示,并将ToolbarControl的伙伴控件设为axMapControl1。
图2添加按钮1.2代码添加及解释鹰眼用来显示主窗体当前视图范围在全景视图中的位置,在ArcMap中使用一个线框在鹰眼视图中标识。
当主视图中的视图范围改变时,鹰眼中的线框随之改变,当拖动鹰眼视图中的红线框时,主视图中的视图范围也随之改变。
下面开始实现鹰眼功能,添加using ESRI.ArcGIS.Carto、using ESRI.ArcGIS.Geometry、using ESRI.ArcGIS.Display三个引用。
首先在axMapControl1中视图范围改变时鹰眼窗体要做出对应的响应,即绘制线框并显示,在OnExtentUpdated事件中添加代码如下:private void axMapControl1_OnExtentUpdated(object sender,ESRI.ArcGIS.Controls.IMapControlEvents2_OnExtentUpdatedEvent e){//创建鹰眼中线框IEnvelope pEnv = (IEnvelope)e.newEnvelope;IRectangleElement pRectangleEle = new RectangleElementClass();IElement pEle = pRectangleEle as IElement;pEle.Geometry = pEnv;//设置线框的边线对象,包括颜色和线宽IRgbColor pColor = new RgbColorClass();pColor.Red = 255;pColor.Green = 0;pColor.Blue = 0;pColor.Transparency = 255;// 产生一个线符号对象ILineSymbol pOutline = new SimpleLineSymbolClass();pOutline.Width = 2;pOutline.Color = pColor;// 设置颜色属性pColor.Red = 255;pColor.Green = 0;pColor.Blue = 0;pColor.Transparency = 0;// 设置线框填充符号的属性IFillSymbol pFillSymbol = new SimpleFillSymbolClass();pFillSymbol.Color = pColor;pFillSymbol.Outline = pOutline;IFillShapeElement pFillShapeEle = pEle as IFillShapeElement;pFillShapeEle.Symbol = pFillSymbol;// 得到鹰眼视图中的图形元素容器IGraphicsContainer pGra = axMapControl2.Map as IGraphicsContainer;IActiveView pAv = pGra as IActiveView;// 在绘制前,清除axMapControl2 中的任何图形元素pGra.DeleteAllElements();// 鹰眼视图中添加线框pGra.AddElement((IElement)pFillShapeEle, 0);// 刷新鹰眼pAv.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);}当鼠标点击鹰眼窗体时,主窗体Extent随之改变。
C# GIS二次开发代码3
Line 和 polygon 与 point 相似 在窗体的 load 事件中添加代码如下 private void ColorSelection_Load(object sender, EventArgs e) { //点的初始颜色,文本框初始值 txtPointRed.Text = MainFrm.pointR.ToString(); txtPointGreen.Text = MainFrm.pointG.ToString(); txtPointBlue.Text = MainFrm.pointB.ToString(); //设置按钮的背景色 btnPointColor.BackColor = Color.FromArgb(MainFrm.pointR, MainFrm.pointG, MainFrm.pointB); } 给 btnPointColor 注册单击事件,代码如下 private void btnPointColor_Click(object sender, EventArgs e) { ColorDialog cd = new ColorDialog();
1、颜色选择器
添加窗体,name 为 ColorSelection,具体控件如下 控件名 GroupBox 3 个 Label 3 个 TextBox Button Button Name 随意 随意 txtPointRed、 txtPointGreen、txtPointBlue btnPointColor btnOK 备注 一个容器 Text 分别为 Red、Green、 Blue RGB 显示颜色 Text:OK; 最下方的按钮
m_pMapControl.MousePointer = esriControlsMousePointer.esriPointerDefault; } } private void mapGIS_OnBeforeScreenDraw(object sender, IMapControlEvents2_OnBeforeScreenDrawEvent e) { if (m_bRoating == false) { m_pMapControl.MousePointer = esriControlsMousePointer.esriPointerHourglass ; } } Private void mapGIS_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e) { if (m_bRoating == false) return; IPoint pPoint; pPoint=new PointClass(); pPoint.PutCoords(e.mapX,e.mapY); m_pMapControl.ActiveView.ScreenDisplay.RotateMoveTo(pPoint); m_pMapControl.ActiveView.ScreenDisplay.RotateTimer(); } private void mapGIS_OnMouseUp(object sender, IMapControlEvents2_OnMouseUpEvent e) { //旋转标志 if (m_bRoating == false) return; m_bRoating = false; double dRotationAngle; dRotationAngle = m_pMapControl.ActiveView.ScreenDisplay.RotateStop(); m_pMapControl.Rotation = dRotationAngle; m_pMapControl.Refresh(esriViewDrawPhase.esriViewGeography); }
C# GIS二次开发代码2
状态栏与右键菜单
在状态栏 statusGIS 中添加 toolStripStatusLabel1,name 改为 tssInform; 在 mainFrm 中添加一个右键菜单 ContexMenuStrip,name 改为 ctmToc; 引入命名空间using ESRI.ArcGIS.Controls; 添加全局变量public int lyrIndex; 在主窗体的 load 事件中将右键菜单与 tocGIS 关联,代码如下: this.tocGIS.ContextMenuStrip = this.ctmToc; 在 mainFrm 中,给 tocGIS 注册单击事件,代码如下 private void tocGIS_OnMouseDown(object sender, ESRI.ArcGIS.Controls.ITOCControlEvents_OnMouseDownEvent e) { esriTOCControlItem toccItem = esriTOCControlItem.esriTOCControlItemNone; ILayer pLyr = null; System.Object pIndex = null; System.Object pOther = null; IBasicMap pMap = null; //tocGIS.HitTest(int x, int y, ref esriTOCControlItem itemType, ref IBasicMap basicMap, ref ILayer layer, ref object unk, ref object data) //获取图层相关信息 tocGIS.HitTest(e.x, e.y, ref toccItem, ref pMap, ref pLyr, ref pOther, ref pIndex); //防止鼠标在空白处点击抛出的异常 try { for (int i = 0; i < yerCount - 1; i++) { //确定索引 if (yer[i].Name == ) lyrIndex = i; }
gis二次开发编程语言
变量与常量的应用实验一:VBA中变量及Inputbox的应用实验目的:熟悉掌握Inputbox的实例编程Option ExplicitSub test()Dim M As StringDim N As StringM = InputBox("请输入用户名:")N = InputBox("请输入密码:")MsgBox "您输入的用户名是:" + M + " " + "您输入的密码是: " + NEnd Sub实验二:VBA中数组的定义和使用实验目的:掌握VBA中的数组如何定义和使用以及单引号( ') ,rem的作用等例如:求1——100所有整数的和Sub arr()Dim i As Integer'定义一个整形变量iDim sum As IntegerRem 定义一个整形变量sumDim arr1(1 To 100) As IntegerFor i = 1 To 100arr1(i) = isum = sum + arr1(i)NextMsgBox "您输入的用户名是:" & sumEnd Sub实验三:VBA 中的判断语句实验目的:熟悉掌握If…Then…Else语句和循环语句的使用(1)Sub pandduan()Dim cj As Integer'cj表示成绩的变量cj = InputBox("请输入一个学生的成绩:")If cj >= 60 ThenMsgBox "您的成绩及格"ElseMsgBox "您输入的成绩不及格"End IfEnd Sub(2) Sub chj()Dim cj As Integercj = InputBox("请输入一个学生的成绩:")If cj > 90 ThenMsgBox "A"ElseIf cj > 80 And cj < 90 ThenMsgBox "B"ElseIf cj > 70 And cj < 80 ThenMsgBox "C"ElseIf cj > 60 And cj < 70 ThenMsgBox "D"ElseMsgBox "E"End IfEnd Sub(3) Sub selec()Dim cj As Integercj = InputBox("请输入一个学生的成绩:")Select Case cj \ 10Case 9MsgBox "A"Case 8MsgBox "B"Case 7MsgBox "C"Case 6MsgBox "D"Case ElseMsgBox "E"End SelectEnd Sub实验四:VBA中循环语句的应用实验目的:学会应用For Next 或For Each…Next语句来编写循环语句例如:(1)For Next 语句的应用求1——100所有整数的和Sub forne()Dim i As IntegerDim sum As Integersum = 0For i = 1 To 100sum = sum + iNext iMsgBox sumEnd Sub(2)For Each…Next语句的应用Sub foreach()Dim arr(5) As IntegerDim i As IntegerDim arr01For i = 0 To 5arr(i) = iNext iFor Each arr01 In arrMsgBox arr01NextEnd Sub(3)Do…loop语句的应用Sub doloop()Dim arr(5) As IntegerDim i As IntegerDim n As Integern = 0i = 0Do While i < 5arr(i) = ii = i + 1n = n + 1LoopMsgBox "程序执行的次数是:" & n End Sub(4)while…wend语句应用Sub whilewd()Dim arr(5) As IntegerDim i As IntegerDim n As Integern = 0i = 0While i <= 5arr(i) = ii = i + 1n = n + 1WendMsgBox "程序执行的次数是:" & n End SubVBA中的过程和函数实验一:Sub过程的用法实验目的:Sub 过程的参数有两种传递方式:按值传递(ByVal)和按地址传递(ByRef),熟悉掌握这两种传递方式的编写过程例如:Sub password01(ByVal x As Integer, ByRef y As Integer)If y = 100 Theny = x + yElsey = x - yEnd Ifx = x + 100End SubSub call_password01()Dim x1 As IntegerDim y1 As Integerx1 = 12y1 = 100Call password(x1, y1)MsgBox "x1=" & x1 & " " & "y1=" & y1End Sub实验一:Function函数的用法实验目的:Function函数也有两种传递方式:按值传递(ByVal)和按地址传递(ByRef),熟悉掌握这两种传递方式的编写过程,如:Function password(ByVal x As Integer, ByRef y As Integer) As Boolean If y = 100 Theny = x + yElsey = x - yEnd Ifx = x + 100If y = 150 Thenpassword = TrueElsepassword = FalseEnd IfEnd FunctionSub call_password()Dim x1 As IntegerDim y1 As Integerx1 = 50y1 = 100If password(x1, y1) ThenMsgBox "x1=" & x1 & " " & "y1=" & y1ElseMsgBox "x1=" & x1End IfEnd Sub实验三:VBA中判断语句的应用实验目的:复习并掌握If…Then…Else语句的使用和IsNumeric(x)测试函数应用。
[转]GIS二次开发(C#+AE)
[转]GIS⼆次开发(C#+AE)乘风莫邪原⽂此过程描述了使⽤ArcGIS控件建⽴和部署应⽤的⽅法和步骤。
你可以在下⾯的⽬录下找到相应的样例程序:<</FONT>安装⽬录>/DeveloperKit/Samples/Developer_Guide_Scenarios/ArcGIS_Engine/Building_an_ArcGIS_Control_Application/Map_Viewer注:ArcGIS样例程序不包含在ArcGIS Engine开发⼯具包“典型”安装⽅式中。
如果你没有安装它们,则可以重新运⾏开发⼯具包安装向导,选择“定制”或“修改”⽅式,并选择软件开发包下的样例项进⾏安装。
⼀、项⽬描述利⽤视窗控件建⽴应⽤程序的⽬标是演⽰并使你熟悉在微软Visual Studio .NET API中使⽤标准ArcGIS控件开发和部署GIS应⽤所需的步聚。
本节中使⽤了Visual Studio .NET开发环境中的MapControl、 PageLayoutControl、TOCControl和ToolbarControl等视窗控件。
COM、Java和C++程序员应该参考如下章节:、、和。
本节演⽰了创建查看ArcMap和ArcGIS桌⾯应⽤图形⽂档的GIS应⽤程序的步骤。
此节包含了以下技术:l 在微软Visual Studio .NET中加载和嵌⼊ArcGIS控件。
l 向PageLayoutControl和MapControl中加载图形⽂档。
l 设置ToolbarControl和TOCControl的绑定控件。
l 处理窗⼝缩放。
l 向ToolbarControl添加ArcGIS Engine命令和⼯具。
l 创建弹出式菜单l 在TOCControl中管理标签编辑l 在MapControl中绘制图形。
l 为MapControl、PageLayoutControl和ToolbarControl创建定制⼯具。
ArcGISEngine二次开发——基础篇
ArcGIS Engine二次开发——基础篇1ArcGIS Engine二次开发——基础篇1.1第一个简单的ArcGIS Engine地图显示程序这个例子将引导您创建第一个简单的地图显示程序,并添加基本的缩放和漫游功能。
如果您之前没有接触过ArcGIS Engine的开发,那么这个例子是您迈入ArcGIS Engine二次开发大门的极好例子,将从零开始引导您一步一步完成任务。
1.1.1创建一个新的工程首先打开Microsoft Visual Studio 2005,点击菜单栏中的“文件”—>“新建”—>“项目”,在弹出的对话框中选择新建一个Visual C#的Windows应用程序,之后更改项目名称为“地图浏览”,更改文件的路径为个人实习文件夹,点击“确定”即可。
图1新建项目对话框选中项目“地图浏览”中的窗体“Form1”,修改其Name属性为“MainForm”,Text属性为“地图浏览”,图2窗体命名1.1.2添加控件及引用点击编译器最左侧的“工具箱”(不存在时可通过“视图”“工具箱”打开),在弹出的选择项中找到“ArcGIS Windows Forms”项,单击其中的MapControl,之后在Form1的空白处单击鼠标左键不放并拖拽鼠标,直到调整MapControl到合适的大小再松开鼠标(您也可以直接在工具箱中双击MapControl,该控件则会自动加入到Form1中)。
用同样的方法,再将LicenseControl添加到Form1中。
图3 打开工具箱图4工具箱如果您在工具箱中找不到MapControl,则请依次尝试以下两种解决方案。
首先单击工具栏,待工具箱弹出之后,在工具箱的任意位置上单击鼠标右键,从弹出菜单中选择“重置工具箱”。
如果这一步操作之后仍然无法看到MapControl,则在工具箱的任意位置上单击鼠标右键,找到“常规”选项卡,然后在“常规”选项卡上单击鼠标右键,在弹出菜单中单击“选择项(I)…”,在弹出的对话框中选择“.NET Framework组件”,找到“LicenseControl”和“MapControl”,将这两项前的复选框打上勾,最后点击确定即可(如果在“.NET Framework 组件”这个面板中找不到这两项,则选择“COM 组件”面板,在“ESRI LicenseControl”和“ESRI. MapControl”前面打勾)。
GIS二次开发—专题图主窗体代码
namespace MapLayout.PageLayout{public class PageLayout{#region 打印输出/// <summary>/// pageLayout输出图片/// </summary>/// <returns>ture为成功,false为失败</returns>public static bool ExportMapToImage(AxPageLayoutControl axPageLayoutControl1){try{SaveFileDialog pSaveDialog = new SaveFileDialog();pSaveDialog.FileName = "";pSaveDialog.Filter = "JPG图片(*.JPG)|*.jpg|tif图片(*.tif)|*.tif|PDF文档(*.PDF)|*.pdf";if (pSaveDialog.ShowDialog() == DialogResult.OK){double iScreenDispalyResolution =axPageLayoutControl1.ActiveView.ScreenDisplay.DisplayTransformation.Resolution;IExporter pExporter = null;if (pSaveDialog.FilterIndex == 0){pExporter = new JpegExporterClass();}else if (pSaveDialog.FilterIndex == 1){pExporter = new TiffExporterClass();}else if (pSaveDialog.FilterIndex == 2){pExporter = new PDFExporterClass();}pExporter.ExportFileName = pSaveDialog.FileName;pExporter.Resolution = (short)iScreenDispalyResolution;tagRECT deviceRect =axPageLayoutControl1.ActiveView.ScreenDisplay.DisplayTransformation.get_DeviceFrame();IEnvelope pDeviceEnvelope = new EnvelopeClass();pDeviceEnvelope.PutCoords(deviceRect.left, deviceRect.bottom,deviceRect.right, deviceRect.top);pExporter.PixelBounds = pDeviceEnvelope;ITrackCancel pCancle = new CancelTrackerClass();axPageLayoutControl1.ActiveView.Output(pExporter.StartExporting(),pExporter.Resolution, ref deviceRect, axPageLayoutControl1.ActiveView.Extent, pCancle);Application.DoEvents();pExporter.FinishExporting();return true;}else{return false;}}catch (Exception Err){MessageBox.Show(Err.Message, "输出图片", MessageBoxButtons.OK,rmation);return false;}}///<summary>/// 打印PageLayout/// </summary>/// <param name="pPageLayout">PageLayout对象</param>public static void PrintPageLayout(AxPageLayoutControl pPageLayout){try{if (pPageLayout.Printer != null){IPrinter pPrinter = pPageLayout.Printer;if (pPrinter.Paper.Orientation != pPageLayout.Page.Orientation){pPrinter.Paper.Orientation = pPageLayout.Page.Orientation;}pPageLayout.PrintPageLayout(1, 0, 0);}}catch (Exception Err){MessageBox.Show(Err.Message, "打印", MessageBoxButtons.OK,rmation);}}#endregion#region 添加Element//添加文字public static void AddText(AxPageLayoutControl axPageLayoutControl1, double pagex, double pagey){IActiveView activeView;IGraphicsContainer graphicsContainer;ITextElement textElement;ITextSymbol textSymbol;IRgbColor color;IElement element;IEnvelope envelope;activeView = axPageLayoutControl1.PageLayout as IActiveView;envelope = new EnvelopeClass();//envelope.PutCoords(0, 0, 5, 5);envelope.PutCoords(pagex - 2, pagey - 2, pagex + 2, pagey + 2);textElement = new TextElementClass();element = textElement as IElement;element.Geometry = envelope;textElement.Text = "我的地图";textSymbol = new TextSymbolClass();color = new RgbColorClass();color.Green = 0;color.Blue = 0;color.Red = 0;textSymbol.Color = color as IColor;textSymbol.Size = 30;textElement.Symbol = textSymbol;graphicsContainer = activeView as IGraphicsContainer;graphicsContainer.AddElement(element, 0);axPageLayoutControl1.Refresh();EditIElement(axPageLayoutControl1, pagex, pagey);}//添加图例public static void AddLegend(AxPageLayoutControl axPageLayoutControl1, double pagex, double pagey){#region 原始UID uid;IEnvelope envelope;//IMapSurround mapSurround;IGraphicsContainer graphicsContainer;IMapFrame mapFrame;IMapSurroundFrame mapSurroundFrame;IElement element;ITrackCancel trackCancel;uid = new UIDClass();uid.Value = "esriCarto.legend";envelope = new EnvelopeClass();//envelope.PutCoords(1, 1, 2, 2);envelope.PutCoords(pagex - 2, pagey - 2, pagex + 2, pagey + 2);graphicsContainer = axPageLayoutControl1.PageLayout as IGraphicsContainer;mapFrame = graphicsContainer.FindFrame(axPageLayoutControl1.ActiveView.FocusMap) as IMapFrame;mapSurroundFrame = mapFrame.CreateSurroundFrame(uid, null); = "图例";element = mapSurroundFrame as IElement;element.Geometry = envelope;element.Activate(axPageLayoutControl1.ActiveView.ScreenDisplay);trackCancel = new CancelTrackerClass();element.Draw(axPageLayoutControl1.ActiveView.ScreenDisplay, trackCancel);graphicsContainer.AddElement(element, 0);axPageLayoutControl1.Refresh();EditIElement(axPageLayoutControl1, pagex, pagey);#endregion//ComDll.Legend.UI.CustomLegendFrm frm = new ComDll.Legend.UI.CustomLegendFrm(axPageLayoutControl1);//frm.ShowDialog();}private void AddLegendToPageLayout(IPageLayout pPageLayout, IEnvelope pEnvelope){try{IActiveView pActiveView = pPageLayout as IActiveView;IMap pMap = pActiveView.FocusMap;IGraphicsContainer pGraphicsContainer = pActiveView as IGraphicsContainer;IMapFrame pMapFrame = pGraphicsContainer.FindFrame(pMap) as IMapFrame;UID pUID = new UID();pUID.Value = "{7A3F91E4-B9E3-11d1-8756-0000F8751720}";ISymbolBackground pSymbolBackground = new SymbolBackgroundClass();IFillSymbol pFillSymbol = new SimpleFillSymbolClass();ILineSymbol pLineSymbol = new SimpleLineSymbolClass();pFillSymbol.Color = Function.GetIRGBColor(255, 255, 255);pLineSymbol.Color = Function.GetIRGBColor(255, 255, 255);pFillSymbol.Outline = pLineSymbol;pSymbolBackground.FillSymbol = pFillSymbol;IMapSurroundFrame pMapSurroundFrame = pMapFrame.CreateSurroundFrame(pUID, null);pMapSurroundFrame.Background = pSymbolBackground;IElement pElement = pMapSurroundFrame as IElement;pElement.Geometry = pEnvelope;IMapSurround pMapSurround = pMapSurroundFrame.MapSurround;ILegend pLegend = pMapSurround as ILegend;pLegend.ClearItems();pLegend.Title = "图例";ITextSymbol pTextSymbol = new TextSymbolClass();pTextSymbol.Size = 10;pTextSymbol.HorizontalAlignment = esriTextHorizontalAlignment.esriTHALeft;ILegendItem pLegendItem = null;for (int i = 0; i < yerCount; i++){ILayer pLayer = pActiveView.FocusMap.get_Layer(i);if (pLayer is IFeatureLayer){IFeatureLayer pFLayer = pLayer as IFeatureLayer;IFeatureClass pFeatureClass = pFLayer.FeatureClass;if (pFeatureClass.FeatureType == esriFeatureType.esriFTAnnotation){continue;}else{pLegendItem = new HorizontalBarLegendItemClass();yer = pLayer;pLegendItem.Columns = 1;pLegendItem.ShowDescriptions = false;pLegendItem.ShowHeading = false;pLegendItem.ShowLabels = true;yerNameSymbol = pTextSymbol;pLegend.AddItem(pLegendItem);}}}}catch (Exception ex){MessageBox.Show(ex.Message);}}//添加图形比例尺public static void AddScaleBar(AxPageLayoutControl axPageLayoutControl1, double pagex, double pagey){UID uid;IEnvelope envelope;//IMapSurround mapSurround;IGraphicsContainer graphicsContainer;IMapFrame mapFrame;IMapSurroundFrame mapSurroundFrame;IElement element;ITrackCancel trackCancel;uid = new UIDClass();uid.Value = "esriCarto.ScaleLine";envelope = new EnvelopeClass();//envelope.PutCoords(1, 1, 10, 2);envelope.PutCoords(pagex - 2, pagey - 2, pagex + 2, pagey + 2);graphicsContainer = axPageLayoutControl1.PageLayout as IGraphicsContainer;mapFrame = graphicsContainer.FindFrame(axPageLayoutControl1.ActiveView.FocusMap) as IMapFrame;mapSurroundFrame = mapFrame.CreateSurroundFrame(uid, null);element = mapSurroundFrame as IElement;element.Geometry = envelope;element.Activate(axPageLayoutControl1.ActiveView.ScreenDisplay);trackCancel = new CancelTrackerClass();element.Draw(axPageLayoutControl1.ActiveView.ScreenDisplay, trackCancel);graphicsContainer.AddElement(element, 0);axPageLayoutControl1.Refresh();}//添加文字比例尺public static void AddScaleText(AxPageLayoutControl axPageLayoutControl1, double pagex, double pagey){UID uid;IEnvelope envelope;// mapSurround;IGraphicsContainer graphicsContainer;IMapFrame mapFrame;IMapSurroundFrame mapSurroundFrame;IElement element;ITrackCancel trackCancel;uid = new UIDClass();uid.Value = "esriCarto.ScaleText";envelope = new EnvelopeClass();//envelope.PutCoords(1, 1, 2, 2);envelope.PutCoords(pagex - 2, pagey - 2, pagex + 2, pagey + 2);graphicsContainer = axPageLayoutControl1.PageLayout as IGraphicsContainer;mapFrame = graphicsContainer.FindFrame(axPageLayoutControl1.ActiveView.FocusMap) as IMapFrame;mapSurroundFrame = mapFrame.CreateSurroundFrame(uid, null);element = mapSurroundFrame as IElement;element.Geometry = envelope;element.Activate(axPageLayoutControl1.ActiveView.ScreenDisplay);trackCancel = new CancelTrackerClass();element.Draw(axPageLayoutControl1.ActiveView.ScreenDisplay, trackCancel);graphicsContainer.AddElement(element, 0);axPageLayoutControl1.Refresh();}//添加标题public static void AddTitle(AxPageLayoutControl axPageLayoutControl1, double pagex, double pagey){MessageBox.Show("添加标题功能类似添加文本,请直接添加文本吧","^o^");}//添加指北针public static void AddNorthArrow(AxPageLayoutControl axPageLayoutControl1, double pagex, double pagey){IEnvelope envelope = new EnvelopeClass();IUID uid = new UIDClass();IGraphicsContainer graphicsContainer;IMapFrame mapFrame;IMapSurroundFrame mapSurroundFrame;IElement element;IMapSurround mapSurround;IMarkerNorthArrow markerNorthArrow;IMarkerSymbol markerSymbol;ICharacterMarkerSymbol characterMarkerSymbol;uid.Value = "esriCarto.MarkerNorthArrow";envelope.PutCoords(pagex - 2, pagey - 2, pagex + 2, pagey + 2);graphicsContainer = axPageLayoutControl1.PageLayout as IGraphicsContainer;mapFrame = graphicsContainer.FindFrame(axPageLayoutControl1.ActiveView.FocusMap) as IMapFrame;mapSurroundFrame = mapFrame.CreateSurroundFrame(uid as UID, null); // Dynamic Castelement = mapSurroundFrame as IElement; // Dynamic Castelement.Geometry = envelope;element.Activate(axPageLayoutControl1.ActiveView.ScreenDisplay);graphicsContainer.AddElement(element, 0);mapSurround = mapSurroundFrame.MapSurround;// Change out the default north arrowmarkerNorthArrow = mapSurround as IMarkerNorthArrow; // Dynamic CastmarkerSymbol = markerNorthArrow.MarkerSymbol;characterMarkerSymbol = markerSymbol as ICharacterMarkerSymbol; // Dynamic CastcharacterMarkerSymbol.CharacterIndex = 200; // change the symbol for the North ArrowmarkerNorthArrow.MarkerSymbol = characterMarkerSymbol;}//添加网格public static void AddNetGird(AxPageLayoutControl axPageLayoutControl1, double pagex, double pagey){IMapGrid mapGrid = new GraticuleClass(); = "Map Grid";//Create a color.IColor color = new RgbColorClass();//color.RGB = 0XBBBBBB; // -> Gray.color = Function.GetIRGBColor(205, 205, 205);//灰色//Set the line symbol used to draw the grid.ICartographicLineSymbol cartographicLineSymbol = new CartographicLineSymbolClass();cartographicLineSymbol.Cap = esriLineCapStyle.esriLCSButt;cartographicLineSymbol.Width = 0.5;cartographicLineSymbol.Color = color;mapGrid.LineSymbol = cartographicLineSymbol as ILineSymbol;mapGrid.Border = null; // Clear the default frame border.//Set the Tick properties.mapGrid.TickLength = 15;cartographicLineSymbol = new CartographicLineSymbolClass();cartographicLineSymbol.Cap = esriLineCapStyle.esriLCSButt;cartographicLineSymbol.Width = 1;cartographicLineSymbol.Color = color;mapGrid.TickLineSymbol = cartographicLineSymbol as ILineSymbol;mapGrid.TickMarkSymbol = null;//Set the SubTick properties.mapGrid.SubTickCount = 5;mapGrid.SubTickLength = 10;cartographicLineSymbol = new CartographicLineSymbolClass();cartographicLineSymbol.Cap = esriLineCapStyle.esriLCSButt;cartographicLineSymbol.Width = 0.2;cartographicLineSymbol.Color = color;mapGrid.SubTickLineSymbol = cartographicLineSymbol as ILineSymbol;// Set the Grid label properties.IGridLabel gridLabel = belFormat;belOffset = 15;//Set the Tick, SubTick, and Label Visibility along the four sides of the grid.mapGrid.SetTickVisibility(true, true, true, true);mapGrid.SetSubTickVisibility(true, true, true, true);mapGrid.SetLabelVisibility(true, true, true, true);//Make the map grid visible so it gets drawn when Active View is updated.mapGrid.Visible = true;//Set the IMeasuredGrid properties.IMeasuredGrid measuredGrid = mapGrid as IMeasuredGrid;measuredGrid.FixedOrigin = true;measuredGrid.XIntervalSize = 10; //Meridian interval.measuredGrid.XOrigin = 5; //Shift grid 5°.measuredGrid.YIntervalSize = 10; //Parallel interval.measuredGrid.YOrigin = 5; //Shift grid 5°.// Add the grid to the MapFrame.IMap map = axPageLayoutControl1.ActiveView.FocusMap;IGraphicsContainer graphicsContainer = axPageLayoutControl1.PageLayout as IGraphicsContainer;IFrameElement frameElement = graphicsContainer.FindFrame(map);IMapFrame mapFrame = frameElement as IMapFrame;IMapGrids mapGrids = null;mapGrids = mapFrame as IMapGrids;mapGrids.AddMapGrid(mapGrid);//Refresh the view.axPageLayoutControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewBackground, null, null);}//添加边框public static void AddNeatLine(AxPageLayoutControl axPageLayoutControl1, double pagex, double pagey){IFrameElement frameElement = axPageLayoutControl1.GraphicsContainer.FindFrame(axPageLayoutControl1.ActiveView.FocusMa p);IFrameElement ife = new FrameElementClass();IRgbColor color = Function.GetIRGBColor(255, 0, 0);ILineSymbol lineSymbol = new SimpleLineSymbolClass();lineSymbol.Color = color;lineSymbol.Width = 2;ISymbolBorder symbolBorder = new SymbolBorderClass();symbolBorder.LineSymbol = lineSymbol;//IEnvelope envelope = new EnvelopeClass();//envelope.PutCoords(pagex - 2, pagey - 2, pagex + 2, pagey + 2);////element.Geometry = envelope;IFrameProperties frameProperties = frameElement as IFrameProperties;frameProperties.Border = symbolBorder;axPageLayoutControl1.ActiveView.Refresh();}//添加图片public static void AddPicture(AxPageLayoutControl axPageLayoutControl1, double pagex, double pagey){IPageLayout pPageLayout;IGraphicsContainer pGraphicsContainer;IActiveView pActiveView;IEnvelope envelope;IElement pEle;IPictureElement pBmpPicEle;pPageLayout = axPageLayoutControl1.PageLayout;pGraphicsContainer = pPageLayout as IGraphicsContainer;pActiveView = pPageLayout as IActiveView;pBmpPicEle = new BmpPictureElementClass();string _picPath = Function.GetOpenFileDialogPath("请选择要添加的图片", "", "位图文件(*.bmp)|*.bmp");if (_picPath == ""){MessageBox.Show("请正确选择图片", "错误");return;}pBmpPicEle.ImportPictureFromFile(_picPath);pBmpPicEle.MaintainAspectRatio = false;//pEnv = axPageLayoutControl1.TrackRectangle();envelope = new EnvelopeClass();envelope.PutCoords(pagex - 2, pagey - 2, pagex + 2, pagey + 2);pEle = pBmpPicEle as IElement;pEle.Geometry = envelope;pGraphicsContainer.AddElement(pEle, 0);pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);}#endregion#region 查找Element,并进行修改public static void EditIElement(AxPageLayoutControl axPageLayoutControl1, double pagex, double pagey){IElement pelement, selectElement = null;IGraphicsContainerSelect pGraphicsContainerSelect = axPageLayoutControl1.PageLayout as IGraphicsContainerSelect;IGraphicsContainer pGraphicsContainer = axPageLayoutControl1.PageLayout as IGraphicsContainer;pGraphicsContainer.Reset();pelement = pGraphicsContainer.Next();#region 查找pelement是否匹配相关元素while (pelement != null){if (pelement.HitTest(pagex, pagey, 0.1)){if (pelement is ITextElement){selectElement = pelement;}else if (pelement is IMapSurroundFrame){IMapSurroundFrame pMapSf = pelement as IMapSurroundFrame;IMapSurround pMapSurround = pMapSf.MapSurround;if (pMapSurround is ILegend){selectElement = pelement;}else if (pMapSurround is IScaleBar){selectElement = pelement;}else if (pMapSurround is IMarkerNorthArrow){selectElement = pelement;}}else if (pelement is IPictureElement){selectElement = pelement;}}pelement = pGraphicsContainer.Next();}#endregion#region 根据匹配结果弹出相应设置界面if (selectElement is ITextElement) //文本元素{//frmITextAttrib itextattrib = new frmITextAttrib(axPageLayoutControl1, selectElement as ITextElement);//itextattrib.Visible = true;MessageBox.Show("找到文本,但是还不能修改");}else if (selectElement is IMapSurroundFrame) //IMapSurroundFrame{IMapSurroundFrame pMapSf = selectElement as IMapSurroundFrame;IMapSurround pMapSurround = pMapSf.MapSurround;if (pMapSurround is ILegend) //图例{//frmILegendAttrib ilegendattrib = new frmILegendAttrib(axPageLayoutControl1);//ilegendattrib.Visible = true;MessageBox.Show("找到图例,但是还不能修改");}else if (pMapSurround is IScaleBar) //图形比例尺{//MessageBox.Show("找到图形比例尺,但是还不能修改");}else if (pMapSurround is IMarkerNorthArrow) //指北针{//frmIMarkerNorthArrowAttrib imarkernortharrow = new frmIMarkerNorthArrowAttrib(axPageLayoutControl1,selectElement);//imarkernortharrow.Visible = true;MessageBox.Show("找到指北针,但是还不能修改");}}else if (selectElement is IPictureElement) //图片{string _picPath = Function.GetOpenFileDialogPath("请选择要添加的图片", "", "位图文件(*.bmp)|*.bmp");if (_picPath == ""){MessageBox.Show("请正确选择图片", "错误");return;}IPictureElement pBmpPicEle;pBmpPicEle = selectElement as IPictureElement;pBmpPicEle.ImportPictureFromFile(_picPath);pelement = pBmpPicEle as IElement;pGraphicsContainer.UpdateElement(pelement);axPageLayoutControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);}#endregion}#endregion}}。
GIS二次开发一些代码
实验一在控制台界面实现加减乘除的四则运算功能,即输入参与计算数值,输出完成的计算结果。
using System;using System.Collections.Generic;using System.Text;namespace 示例1{class Program{static void Main(string[] args){string a;string b;string c;double d = 0;Console.WriteLine("请输入第一个数字");a = Console.ReadLine();Console.WriteLine("请输入运算符");b = Console.ReadLine();Console.WriteLine("请输入第二个数字");c = Console.ReadLine();if (b == "+")d = double.Parse(a) + double.Parse(c);Console.WriteLine("结果为:{0}", d);Console.ReadLine();if (b == "-")d = double.Parse(a) - double.Parse(c);Console.WriteLine("结果为:{0}", d);Console.ReadLine();if (b == "*")d = double.Parse(a) * double.Parse(c);Console.WriteLine("结果为:{0}", d);Console.ReadLine();if (b == "/")d = double.Parse(a) / double.Parse(c);Console.WriteLine("结果为:{0}", d);Console.ReadLine();}}}创建Windows程序,按Button按钮,出现MessageBox信息框using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace 示例2{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){MessageBox.Show("欢迎学习GIS二次开发", "提示");}}}实验二Windows应用程序,利用TextBox控件和窗体Form的Form1_Load事件练习String.Format的格式化输出。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
1、保存栅格数据(注意:保存的时候不要忘记要将栅格数据保存到栅格数据集工作空间中,同时还有栅格的扩展名一定要加上。
)Public Sub SaveRaster()Dim pMxDoc As IMxDocumentDim pMap As IMapSet pMxDoc = Application.DocumentSet pMap = pMxDoc.FocusMappMap.DeleteLayer yer(0)Dim pRasterDataset As IRasterDatasetDim pWks As IRasterWorkspaceDim pWksFact As IWorkspaceFactorySet pWksFact = New RasterWorkspaceFactorySet pWks = pWksFact.OpenFromFile("D:\Projects\ZLS\temp", 0)Dim pRBC As IRasterBandCollectionSet pRasterDataset = pWks.OpenRasterDataset("test")'Dim pRBC As IRasterBandCollectionDim pRLayer As IRasterLayerSet pRLayer = New RasterLayerpRLayer.CreateFromDataset pRasterDatasetDim pRaster As IRasterSet pRaster = pRLayer.RasterSet pRBC = pRasterDim pDs As IDatasetSet pDs = pRBC.SaveAs("test", pWks, "TIFF") copyright pMap.AddLayer pRLayerEnd Sub2、根据已有数据字段,创建shape文件,并将数据插入到shape文件中(delphi代码)function CreateNewShape(pCursor: IFeatureCursor; pFCls: IFeatureClass; pPath: WideString; pNewFClsName:WideString): IFeatureClass;varpShapeFieldName, ConfigKeyword: WideString;pNewFCls: IFeatureClass;pFeature: IFeature;pNewFCursor: IFeatureCursor;pFeatureBuffer: IFeatureBuffer;pFields: IFields;pShape: IGeometry;pGeoType: esriGeometryType;pWFact: IWorkspaceFactory;pWorkspace: IWorkspace;pWorkspaceEdit: IWorkspaceEdit;pFWks: IFeatureWorkspace;pDataset: IDataset;pCLSID: IUID;pEXTCLSID: IUID;pNewID: OleVariant;bl: wordbool;i, pFieldCount: integer;pValue: OleVariant;beginConfigKeyword := '';//Determine the appropriate geometry type corresponding the the feature typeif pCLSID = nil thenbeginpFCls.Get_CLSID(pCLSID);pFCls.Get_ShapeType(pGeoType);end;//create fields collectionif pFields = nil thenbeginpFCls.Get_Fields(pFields);end;//get geometry field namepFCls.Get_ShapeFieldName(pShapeFieldName);pEXTCLSID := nil;pWFact:=CoshapefileWorkspaceFactory.create as IWorkspaceFactory;pWFact.OpenFromFile(pPath, 0, pWorkspace);pFWks := pWorkspace as IFeatureWorkspace;bl := NameExits(pWorkspace, pNewFClsName);//create shapefile in the temp folderif not bl thenbeginpFWks.CreateFeatureClass(pNewFClsName, pFields, pCLSID, pEXTCLSID, pGeoType, pShapeFieldName,ConfigKeyword, pNewFCls);endelsebeginpFWks.OpenFeatureClass(pNewFClsName, pNewFCls);pDataset := pNewFCls as IDataset;pDataset.Delete; copyright pFWks.CreateFeatureClass(pNewFClsName, pFields, pCLSID, pEXTCLSID, pGeoType, pShapeFieldName,ConfigKeyword, pNewFCls);end;//Add the features to this ShapeFilepWorkspaceEdit := pWorkspace as IWorkspaceEdit;pWorkspaceEdit.StartEditing(true);pWorkspaceEdit.StartEditOperation;pNewFCls.CreateFeatureBuffer(pFeatureBuffer);pNewFCls.Insert(true, pNewFCursor);pCursor.NextFeature(pFeature);pFeature.Get_Fields(pFields);pFields.Get_FieldCount(pFieldCount);while not (pFeature = nil) dobeginfor i := 0 to pFieldCount - 1 dobeginpFeature.Get_Value(i, pValue);pFeatureBuffer.Set_Value(i, pValue);end;内容来自GIS公园pFeature.Get_Shape(pShape);pFeatureBuffer.Set_Shape(pShape);pNewFCursor.InsertFeature(pFeatureBuffer, pNewID);pCursor.NextFeature(pFeature);end;pNewFCursor.Flush;pWorkspaceEdit.StopEditOperation;pWorkspaceEdit.StopEditing(true);//Get ResaultCreateNewShape := pNewFCls;end;3、渲染栅格图层Public Sub SetRasterRenderer()Dim NumOfClass As IntegerNumOfClass = 5' Get MapDim pMxDoc As IMxDocumentSet pMxDoc = ThisDocumentDim pMap As IMapSet pMap = pMxDoc.FocusMap' Get raster input from layerDim pRLayer As IRasterLayerSet pRLayer = yer(0)Dim pRaster As IRasterSet pRaster = pRLayer.Raster' Create classfy renderer and QI RasterRenderer interface Dim pClassRen As IRasterClassifyColorRampRenderer Set pClassRen = New RasterClassifyColorRampRenderer Dim pRasRen As IRasterRendererSet pRasRen = pClassRencopyright ' Set raster for the render and updateSet pRasRen.Raster = pRasterpClassRen.ClassCount = NumOfClasspRasRen.Update' Create a color ramp to useDim pRamp As IAlgorithmicColorRampSet pRamp = New AlgorithmicColorRamppRamp.Size = NumOfClassDim pFColor As IColorDim pTColor As IColorSet pFColor = New RgbColorSet pTColor = New RgbColorpFColor.RGB = RGB(10, 100, 10)pTColor.RGB = RGB(60, 0, 60)pRamp.FromColor = pFColorpRamp.ToColor = pTColorpRamp.CreateRamp True' Create symbol for the classesDim pFSymbol As IFillSymbolSet pFSymbol = New SimpleFillSymbol' loop through the classes and apply the color and label Dim i As IntegerFor i = 0 To pClassRen.ClassCount - 1pFSymbol.Color = pRamp.Color(i)pClassRen.Symbol(i) = pFSymbolbel(i) = "Class" & CStr(i)Next i' Update the renderer and plug into layerpRasRen.UpdateSet pRLayer.Renderer = pClassRenpMxDoc.ActiveView.RefreshpMxDoc.UpdateContents' Release memeorySet pMxDoc = Nothing本文来GIS公园Set pMap = NothingSet pRLayer = NothingSet pRaster = NothingSet pRasRen = NothingSet pClassRen = NothingSet pRamp = NothingSet pFSymbol = Nothing End Sub内容来自GIS公园。