performLayout

本文详细剖析了Android中视图的布局流程,包括初始化后的DecorView如何调用performTraversals(),以及performLayout如何通过view的layout方法来确定子view的位置。文章深入探讨了TextView和不同ViewGroup如FrameLayout及LinearLayout在onLayout中的实现细节。
  1. 初始化app后DecorView调用performTraversals(),执行完performMeasure后开始执行
    performLayout(lp, mWidthmHeight);
  2. performLayout里面调用了 view的layout方法
    host.layout(00, host.getMeasuredWidth(), host.getMeasuredHeight());
  3. 先看viewGroup的处理,里面包含两个函数:
    1. layout调用了view.layout
      super.layout(l, t, r, b)
    2. onLayout
      abstract方法,需要子类实现
  4. 所有的方法最终都是调用了view的layout,接下来看view的layout方法
    onLayout(changed, l, t, r, b)
    调用用了onLayout,而onLayout为空方法。
  5. 到这里layout执行完了,没有实现功能,说明layout的计算是在具体的view里面实现的
  6. 接下来分别看一下TextView和FrameLayout的onLayout方法
    1. TextView
      @Override
      protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
          super.onLayout(changed, left, top, right, bottom);
          if (mDeferScroll >= 0) {
              int curs = mDeferScroll;
              mDeferScroll = -1;
              bringPointIntoView(Math.min(curs, mText.length()));
          }
      }


      很简单,直接交给了super即view进行处理,原因很简单:对于单个view(没有子view)来说,只要按照父view传给的ltrb(left、top、right、bottom layout的四个参数)进行处理就好了,并不需要自己本身去计算
    2. FrameLayout
      1. void layoutChildren(int left, int top, int right, int bottom, boolean forceLeftGravity) {
            final int count = getChildCount();
        
            final int parentLeft = getPaddingLeftWithForeground();
            final int parentRight = right - left - getPaddingRightWithForeground();
        
            final int parentTop = getPaddingTopWithForeground();
            final int parentBottom = bottom - top - getPaddingBottomWithForeground();
        
            for (int i = 0; i < count; i++) {
                final View child = getChildAt(i);
                if (child.getVisibility() != GONE) {
                    final LayoutParams lp = (LayoutParams) child.getLayoutParams();
        
                    final int width = child.getMeasuredWidth();
                    final int height = child.getMeasuredHeight();
        
                    int childLeft;
                    int childTop;
        
                    int gravity = lp.gravity;
                    if (gravity == -1) {
                        gravity = DEFAULT_CHILD_GRAVITY;
                    }
        
                    final int layoutDirection = getLayoutDirection();
                    final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
                    final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
        
                    switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                        case Gravity.CENTER_HORIZONTAL:
                            childLeft = parentLeft + (parentRight - parentLeft - width) / 2 +
                            lp.leftMargin - lp.rightMargin;
                            break;
                        case Gravity.RIGHT:
                            if (!forceLeftGravity) {
                                childLeft = parentRight - width - lp.rightMargin;
                                break;
                            }
                        case Gravity.LEFT:
                        default:
                            childLeft = parentLeft + lp.leftMargin;
                    }
        
                    switch (verticalGravity) {
                        case Gravity.TOP:
                            childTop = parentTop + lp.topMargin;
                            break;
                        case Gravity.CENTER_VERTICAL:
                            childTop = parentTop + (parentBottom - parentTop - height) / 2 +
                            lp.topMargin - lp.bottomMargin;
                            break;
                        case Gravity.BOTTOM:
                            childTop = parentBottom - height - lp.bottomMargin;
                            break;
                        default:
                            childTop = parentTop + lp.topMargin;
                    }
        
                    child.layout(childLeft, childTop, childLeft + width, childTop + height);
                }
            }
        }


      2. 逻辑很清楚,遍历child,获得child的measureWidth和measureHeight和layoutparam,根据gravity计算childLeft和childTop,另外两个参数直接通过width和height计算获得。
      3. 最后调用child.layout进行处理
      4. 不同的viewgrouop由于自身不同的规则会在onLayout进行处理,这里的fragmeLayout比较简单,没有考虑同一个viewGroup之下的子view之间的互相影响,下面看一下LinearLayout
    3. LinearLayout
      1. @Override
        protected void onLayout(boolean changed, int l, int t, int r, int b) {
            if (mOrientation == VERTICAL) {
                layoutVertical(l, t, r, b);
            } else {
                layoutHorizontal(l, t, r, b);
            }
        }
      2. 首先根据orientation进行区分,没毛病
      3. 看一下 layoutHorizontal
      4. void layoutHorizontal(int left, int top, int right, int bottom) {
            final boolean isLayoutRtl = isLayoutRtl();
            final int paddingTop = mPaddingTop;
        
            int childTop;
            int childLeft;
           
            // Where bottom of child should go
            final int height = bottom - top;
            int childBottom = height - mPaddingBottom; 
           
            // Space available for child
            int childSpace = height - paddingTop - mPaddingBottom;
        
            final int count = getVirtualChildCount();
        
            final int majorGravity = mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK;
            final int minorGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
        
            final boolean baselineAligned = mBaselineAligned;
        
            final int[] maxAscent = mMaxAscent;
            final int[] maxDescent = mMaxDescent;
        
            final int layoutDirection = getLayoutDirection();
            switch (Gravity.getAbsoluteGravity(majorGravity, layoutDirection)) {
                case Gravity.RIGHT:
                    // mTotalLength contains the padding already
                    childLeft = mPaddingLeft + right - left - mTotalLength;
                    break;
        
                case Gravity.CENTER_HORIZONTAL:
                    // mTotalLength contains the padding already
                    childLeft = mPaddingLeft + (right - left - mTotalLength) / 2;
                    break;
        
                case Gravity.LEFT:
                default:
                    childLeft = mPaddingLeft;
                    break;
            }
        
            int start = 0;
            int dir = 1;
            //In case of RTL, start drawing from the last child.
            if (isLayoutRtl) {
                start = count - 1;
                dir = -1;
            }
        
            for (int i = 0; i < count; i++) {
                final int childIndex = start + dir * i;
                final View child = getVirtualChildAt(childIndex);
                if (child == null) {
                    childLeft += measureNullChild(childIndex);
                } else if (child.getVisibility() != GONE) {
                    final int childWidth = child.getMeasuredWidth();
                    final int childHeight = child.getMeasuredHeight();
                    int childBaseline = -1;
        
                    final LinearLayout.LayoutParams lp =
                            (LinearLayout.LayoutParams) child.getLayoutParams();
        
                    if (baselineAligned && lp.height != LayoutParams.MATCH_PARENT) {
                        childBaseline = child.getBaseline();
                    }
                   
                    int gravity = lp.gravity;
                    if (gravity < 0) {
                        gravity = minorGravity;
                    }
                   
                    switch (gravity & Gravity.VERTICAL_GRAVITY_MASK) {
                        case Gravity.TOP:
                            childTop = paddingTop + lp.topMargin;
                            if (childBaseline != -1) {
                                childTop += maxAscent[INDEX_TOP] - childBaseline;
                            }
                            break;
        
                        case Gravity.CENTER_VERTICAL:
                            // Removed support for baseline alignment when layout_gravity or
                            // gravity == center_vertical. See bug #1038483.
                            // Keep the code around if we need to re-enable this feature
                            // if (childBaseline != -1) {
                            //     // Align baselines vertically only if the child is smaller than us
                            //     if (childSpace - childHeight > 0) {
                            //         childTop = paddingTop + (childSpace / 2) - childBaseline;
                            //     } else {
                            //         childTop = paddingTop + (childSpace - childHeight) / 2;
                            //     }
                            // } else {
                            childTop = paddingTop + ((childSpace - childHeight) / 2)
                                    + lp.topMargin - lp.bottomMargin;
                            break;
        
                        case Gravity.BOTTOM:
                            childTop = childBottom - childHeight - lp.bottomMargin;
                            if (childBaseline != -1) {
                                int descent = child.getMeasuredHeight() - childBaseline;
                                childTop -= (maxDescent[INDEX_BOTTOM] - descent);
                            }
                            break;
                        default:
                            childTop = paddingTop;
                            break;
                    }
        
                    if (hasDividerBeforeChildAt(childIndex)) {
                        childLeft += mDividerWidth;
                    }
        
                    childLeft += lp.leftMargin;
                    setChildFrame(child, childLeft + getLocationOffset(child), childTop,
                            childWidth, childHeight);
                    childLeft += childWidth + lp.rightMargin +
                            getNextLocationOffset(child);
        
                    i += getChildrenSkipCount(child, childIndex);
                }
            }
        }


      5. 代码比较长,逻辑挺简单,拆开看
        1. 获取count(子view个数),childLeft(开始显示子view的left位置)
        2. 遍历child
          1. 和上面一样获取child的measureHeight和measureWidth,说明layout是在measure的基础上的
          2. 累加childLeft,水平的linearlayout子view从左到右依次显示
          3. 最终调用child.layout
  7. 综上layout过程分析完毕,总结一下
    1. 相对于measure,layout过程相对简单,view不需要特殊处理,viewgroup要特殊处理
    2. viewGroup中必须实现onLayout方法,里面根据父view的layoutGravity计算子view的显示区域和开始的显示位置
    3. 遍历view,根据子view的layoutHeigth和layoutWidth以及gravity计算子view位置
    4. 最后说一下getWidth、getHeigth和getMeasureHeight、getMeasureWidth方法
      1. public final int getWidth() {
            return mRight mLeft;
        }
      2. public final int getHeight() {
            return mBottom mTop;
        }
      3. public final int getMeasuredWidth() {
            return mMeasuredWidth MEASURED_SIZE_MASK;
        }
      4. public final int getMeasuredHeight() {
            return mMeasuredHeight MEASURED_SIZE_MASK;
        }
      5. 由上可知getWidth、getHeigth是layout后计算出来的实际值,而getMeasureHeight、getMeasureWidth则是measure计算后获取的理论值
env WINEPREFIX="/home/topeet/.wine" wine /media/topeet/Ventoy/文件/PDFPatcher.1.1.2.4659/PDFPatcher.exe %f 0024:fixme:ntdll:NtQuerySystemInformation info_class SYSTEM_PERFORMANCE_INFORMATION 0024:fixme:font:get_nearest_charset TCI failing on 20000000 0024:fixme:font:get_nearest_charset returning DEFAULT_CHARSET face->fs.fsCsb[0] = 20000000 file = L"Z:\\usr\\share\\fonts\\truetype\\fonts-gujr-extra\\aakar-medium.ttf" 0024:fixme:font:freetype_set_outline_text_metrics failed to read full_nameW for font L"Ani"! 0024:fixme:font:freetype_set_outline_text_metrics failed to read full_nameW for font L"Ani"! 0024:fixme:font:freetype_set_outline_text_metrics failed to read full_nameW for font L"JDBS"! 0024:fixme:font:freetype_set_outline_text_metrics failed to read full_nameW for font L"JDBS"! 0024:fixme:font:freetype_set_outline_text_metrics failed to read full_nameW for font L"JXBS"! 0024:fixme:font:freetype_set_outline_text_metrics failed to read full_nameW for font L"JXBS"! 0024:err:gdiplus:GdipCreateFontFromLogfontW FATAL: Missing 'L"MS Shell Dlg"' font, program may not work properly 0024:err:gdiplus:GdipCreateFontFromLogfontW FATAL: Missing 'L"MS Shell Dlg"' font, program may not work properly 0024:fixme:gdiplus:GdipGetFamilyName No support for handling of multiple languages! 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:gdiplus:GdipCreateFontFromLogfontW FATAL: Missing 'L"MS Shell Dlg"' font, program may not work properly 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" 0024:err:dc:CreateDCW no driver found for L"\\" Unhandled Exception: System.NotImplementedException: The method or operation is not implemented. at System.Drawing.Font.ToLogFont (System.Object logFont, System.Drawing.Graphics graphics) [0x000cc] in <bfeb5fdca71942e18134223465f4f838>:0 at System.Drawing.Font.ToLogFont (System.Object logFont) [0x00012] in <bfeb5fdca71942e18134223465f4f838>:0 at System.Drawing.Font.ToHfont () [0x00010] in <bfeb5fdca71942e18134223465f4f838>:0 at (wrapper remoting-invoke-with-check) System.Drawing.Font.ToHfont() at System.Windows.Forms.Control+FontHandleWrapper..ctor (System.Drawing.Font font) [0x00006] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at (wrapper remoting-invoke-with-check) System.Windows.Forms.Control+FontHandleWrapper..ctor(System.Drawing.Font) at System.Windows.Forms.Control.GetDefaultFontHandleWrapper () [0x0000c] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at System.Windows.Forms.Control.get_FontHandle () [0x000f8] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at System.Windows.Forms.ContainerControl.GetFontAutoScaleDimensions () [0x0002d] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at System.Windows.Forms.ContainerControl.get_CurrentAutoScaleDimensions () [0x0001e] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at System.Windows.Forms.ContainerControl.get_AutoScaleFactor () [0x00000] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at System.Windows.Forms.ContainerControl.OnChildLayoutResuming (System.Windows.Forms.Control child, System.Boolean performLayout) [0x00062] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at System.Windows.Forms.Control.OnLayoutResuming (System.Boolean performLayout) [0x0000e] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at System.Windows.Forms.Control.ResumeLayout (System.Boolean performLayout) [0x00023] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at (wrapper remoting-invoke-with-check) System.Windows.Forms.Control.ResumeLayout(bool) at PDFPatcher.MainForm.InitializeComponent () [0x017ea] in <8a9c318b6a10467f9bc12b3b856064d0>:0 at PDFPatcher.MainForm..ctor () [0x00011] in <8a9c318b6a10467f9bc12b3b856064d0>:0 at (wrapper remoting-invoke-with-check) PDFPatcher.MainForm..ctor() at PDFPatcher.Program.Main (System.String[] args) [0x00028] in <8a9c318b6a10467f9bc12b3b856064d0>:0 [ERROR] FATAL UNHANDLED EXCEPTION: System.NotImplementedException: The method or operation is not implemented. at System.Drawing.Font.ToLogFont (System.Object logFont, System.Drawing.Graphics graphics) [0x000cc] in <bfeb5fdca71942e18134223465f4f838>:0 at System.Drawing.Font.ToLogFont (System.Object logFont) [0x00012] in <bfeb5fdca71942e18134223465f4f838>:0 at System.Drawing.Font.ToHfont () [0x00010] in <bfeb5fdca71942e18134223465f4f838>:0 at (wrapper remoting-invoke-with-check) System.Drawing.Font.ToHfont() at System.Windows.Forms.Control+FontHandleWrapper..ctor (System.Drawing.Font font) [0x00006] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at (wrapper remoting-invoke-with-check) System.Windows.Forms.Control+FontHandleWrapper..ctor(System.Drawing.Font) at System.Windows.Forms.Control.GetDefaultFontHandleWrapper () [0x0000c] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at System.Windows.Forms.Control.get_FontHandle () [0x000f8] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at System.Windows.Forms.ContainerControl.GetFontAutoScaleDimensions () [0x0002d] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at System.Windows.Forms.ContainerControl.get_CurrentAutoScaleDimensions () [0x0001e] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at System.Windows.Forms.ContainerControl.get_AutoScaleFactor () [0x00000] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at System.Windows.Forms.ContainerControl.OnChildLayoutResuming (System.Windows.Forms.Control child, System.Boolean performLayout) [0x00062] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at System.Windows.Forms.Control.OnLayoutResuming (System.Boolean performLayout) [0x0000e] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at System.Windows.Forms.Control.ResumeLayout (System.Boolean performLayout) [0x00023] in <462e49eb7aa34bdea8cf98f8bc777938>:0 at (wrapper remoting-invoke-with-check) System.Windows.Forms.Control.ResumeLayout(bool) at PDFPatcher.MainForm.InitializeComponent () [0x017ea] in <8a9c318b6a10467f9bc12b3b856064d0>:0 at PDFPatcher.MainForm..ctor () [0x00011] in <8a9c318b6a10467f9bc12b3b856064d0>:0 at (wrapper remoting-invoke-with-check) PDFPatcher.MainForm..ctor() ================================================================= Native Crash Reporting ================================================================= Got a UNKNOWN while executing native code. This usually indicates a fatal error in the mono runtime or one of the native libraries used by your application. ================================================================= ================================================================= Managed Stacktrace: ================================================================= at <unknown> <0xffffffff> at Gdip:IntGdipDisposeImage <0x00012> at Gdip:GdipDisposeImage <0x0003b> at System.Drawing.Image:Dispose <0x0008f> at System.Drawing.Image:Finalize <0x0002a> at System.Object:runtime_invoke_virtual_void__this__ <0x0006b> ================================================================= wine: Unhandled page fault on read access to F5AD771E at address 7119C31B (thread 0110), starting debugger... topeet@topeet-pc:~/桌面$
最新发布
10-29
private void GenerateTableFromDataTable(DataTable dataTable) { // 清空现有内容 tableLayoutPanel1.Controls.Clear(); tableLayoutPanel1.RowStyles.Clear(); tableLayoutPanel1.ColumnStyles.Clear(); // 设置列数和均分列宽 int columnCount = dataTable.Columns.Count; tableLayoutPanel1.ColumnCount = columnCount; for (int i = 0; i < columnCount; i++) { tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100f / columnCount)); } // 添加列标题 int headerRowHeight = 40; tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Absolute, headerRowHeight)); for (int i = 0; i < columnCount; i++) { Label headerLabel = new Label { Text = dataTable.Columns[i].ColumnName, Font = new Font("微软雅黑", 10, FontStyle.Bold), TextAlign = ContentAlignment.MiddleCenter, Dock = DockStyle.Fill }; tableLayoutPanel1.Controls.Add(headerLabel, i, 0); } // 添加数据行 int dataRowHeight = 30; int rowIndex = 1; foreach (DataRow row in dataTable.Rows) { tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Absolute, dataRowHeight)); for (int colIndex = 0; colIndex < columnCount; colIndex++) { Label dataLabel = new Label { Text = string.IsNullOrEmpty(row[colIndex].ToString()) ? " " : row[colIndex].ToString(), TextAlign = ContentAlignment.MiddleCenter, Dock = DockStyle.Fill, MinimumSize = new Size(0, dataRowHeight) }; tableLayoutPanel1.Controls.Add(dataLabel, colIndex, rowIndex); } rowIndex++; } // 设置总行数 tableLayoutPanel1.RowCount = rowIndex; // 动态调整 TableLayoutPanel 高度 int totalHeight = headerRowHeight + (dataTable.Rows.Count * dataRowHeight); tableLayoutPanel1.Height = totalHeight; tableLayoutPanel1.Width = panel1.Width - 20; // 强制刷新布局 tableLayoutPanel1.PerformLayout(); panel1.PerformLayout(); }设置panel的颜色是透明的,然后tableLayoutPanel1是透明色
08-01
using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.Geometry; using Autodesk.AutoCAD.Runtime; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Forms; // 为避免命名冲突,创建别名 using AcadApp = Autodesk.AutoCAD.ApplicationServices.Application; using SystemException = System.Exception; [assembly: CommandClass(typeof(CadLibraryPlugin.LibraryCommands))] namespace CadLibraryPlugin { public class LibraryCommands { [CommandMethod("CFS")] public void ShowLibrary() { try { AcadApp.ShowModelessDialog(AcadApp.MainWindow.Handle, new LibraryForm(), false); } catch (SystemException ex) { MessageBox.Show($"打开词库时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } public class TextInfo { public string Name { get; set; } public string Path { get; set; } public bool IsSystemText { get; set; } public string OriginalFileName { get; set; } public string Content { get; set; } public int EntryNumber { get; set; } } public partial class LibraryForm : Form { private string _systemTextsPath; private string _userTextsPath; private string _selectedTextName = string.Empty; private bool _isSystemText = false; private string _selectedTextPath = string.Empty; private string _originalPreviewContent = string.Empty; private Document _currentDoc; public LibraryForm() { InitializeComponent(); InitializeForm(); } private void InitializeForm() { try { InitializePaths(); _currentDoc = AcadApp.DocumentManager.MdiActiveDocument; LoadAllTexts(); btnDelete.Enabled = false; } catch (SystemException ex) { MessageBox.Show($"初始化词库窗体时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void InitializePaths() { try { string pluginPath = System.Reflection.Assembly.GetExecutingAssembly().Location; string pluginDirectory = Path.GetDirectoryName(pluginPath); _systemTextsPath = Path.Combine(pluginDirectory, "ScaffoldBlocks"); if (!Directory.Exists(_systemTextsPath)) { Directory.CreateDirectory(_systemTextsPath); } _userTextsPath = GetBestUserPath(); Directory.CreateDirectory(_userTextsPath); System.Diagnostics.Debug.WriteLine($"系统词库路径: {_systemTextsPath}"); System.Diagnostics.Debug.WriteLine($"用户词库路径: {_userTextsPath}"); } catch (SystemException ex) { MessageBox.Show($"初始化路径时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private string GetBestUserPath() { List<string> potentialPaths = new List<string> { Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "CADTextLibrary"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CADTextLibrary"), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "CADTextLibrary") }; foreach (var path in potentialPaths) { try { string testFile = Path.Combine(path, "test_write_permission.tmp"); Directory.CreateDirectory(path); File.WriteAllText(testFile, "test"); File.Delete(testFile); if (!ContainsChineseCharacters(path)) { return path; } } catch { continue; } } return potentialPaths[0]; } private bool ContainsChineseCharacters(string text) { return text.Any(c => c >= 0x4e00 && c <= 0x9fff); } private void LoadAllTexts() { try { treeViewDirectory.Nodes.Clear(); // 系统词库节点 TreeNode systemNode = new TreeNode("系统词库"); treeViewDirectory.Nodes.Add(systemNode); if (Directory.Exists(_systemTextsPath)) { var systemFiles = Directory.GetFiles(_systemTextsPath, "*.txt"); List<TreeNode> allSystemEntries = new List<TreeNode>(); foreach (string file in systemFiles) { try { var entries = ParseTextFileEntries(file); foreach (var entry in entries) { allSystemEntries.Add(entry); } } catch (SystemException ex) { System.Diagnostics.Debug.WriteLine($"加载系统文本失败 {file}: {ex.Message}"); } } // 为条目编号 for (int i = 0; i < allSystemEntries.Count; i++) { int entryNumber = i + 1; TreeNode entryNode = allSystemEntries[i]; if (entryNode.Tag is TextInfo textInfo) { textInfo.EntryNumber = entryNumber; entryNode.Text = $"{entryNumber}.{textInfo.Name}"; } systemNode.Nodes.Add(entryNode); } if (allSystemEntries.Count == 0) { systemNode.Nodes.Add($"暂无系统文本 (路径: {_systemTextsPath})"); } } else { systemNode.Nodes.Add($"系统词库目录不存在 (路径: {_systemTextsPath})"); } // 用户词库节点 TreeNode userNode = new TreeNode("用户词库"); treeViewDirectory.Nodes.Add(userNode); if (Directory.Exists(_userTextsPath)) { string[] userFiles = Directory.GetFiles(_userTextsPath, "*.txt"); foreach (string file in userFiles) { try { string textName = Path.GetFileNameWithoutExtension(file); string content = File.ReadAllText(file); string displayName = ExtractTitleFromContent(content) ?? textName; TreeNode node = new TreeNode(displayName); node.Tag = new TextInfo { Name = displayName, Path = file, IsSystemText = false, OriginalFileName = textName, Content = content }; userNode.Nodes.Add(node); } catch (SystemException ex) { System.Diagnostics.Debug.WriteLine($"加载用户文本失败 {file}: {ex.Message}"); } } if (userFiles.Length == 0) { userNode.Nodes.Add("暂无用户文本"); } } else { userNode.Nodes.Add("用户词库目录不存在"); } treeViewDirectory.ExpandAll(); } catch (SystemException ex) { MessageBox.Show($"加载文本列表时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private List<TreeNode> ParseTextFileEntries(string filePath) { List<TreeNode> entries = new List<TreeNode>(); string fileName = Path.GetFileNameWithoutExtension(filePath); try { string[] lines = File.ReadAllLines(filePath); List<string> currentEntryLines = new List<string>(); string currentTitle = null; foreach (string line in lines) { string trimmedLine = line.Trim(); if (trimmedLine.StartsWith("《") && trimmedLine.EndsWith("》")) { if (currentTitle != null && currentEntryLines.Count > 0) { entries.Add(CreateEntryNode(currentTitle, currentEntryLines, filePath, fileName)); } currentTitle = trimmedLine.Substring(1, trimmedLine.Length - 2); currentEntryLines = new List<string>(); } else if (currentTitle != null) { currentEntryLines.Add(line); } } if (currentTitle != null && currentEntryLines.Count > 0) { entries.Add(CreateEntryNode(currentTitle, currentEntryLines, filePath, fileName)); } if (entries.Count == 0) { entries.Add(CreateEntryNode(fileName, lines.ToList(), filePath, fileName)); } } catch (SystemException ex) { System.Diagnostics.Debug.WriteLine($"解析文本文件失败 {filePath}: {ex.Message}"); entries.Add(new TreeNode($"错误: 无法解析 {fileName}") { Tag = null }); } return entries; } private TreeNode CreateEntryNode(string title, List<string> contentLines, string filePath, string fileName) { string content = string.Join(Environment.NewLine, contentLines).Trim(); TreeNode node = new TreeNode(title); node.Tag = new TextInfo { Name = title, Path = filePath, IsSystemText = true, OriginalFileName = fileName, Content = content }; return node; } private string ExtractTitleFromContent(string content) { if (string.IsNullOrEmpty(content)) return null; string[] lines = content.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { string trimmedLine = line.Trim(); if (trimmedLine.StartsWith("《") && trimmedLine.EndsWith("》")) { return trimmedLine.Substring(1, trimmedLine.Length - 2); } } return null; } private void btnAdd_Click(object sender, EventArgs e) { Document doc = null; try { doc = AcadApp.DocumentManager.MdiActiveDocument; if (doc == null) { MessageBox.Show("没有打开的AutoCAD文档!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } Editor ed = doc.Editor; PromptSelectionOptions selOpts = new PromptSelectionOptions(); selOpts.MessageForAdding = "选择要入库的文本对象 (支持TEXT和MTEXT): "; selOpts.AllowDuplicates = false; // 选择过滤器 TypedValue[] filterList = new TypedValue[] { new TypedValue((int)DxfCode.Operator, "<or"), new TypedValue((int)DxfCode.Start, "TEXT"), new TypedValue((int)DxfCode.Start, "MTEXT"), new TypedValue((int)DxfCode.Operator, "or>") }; SelectionFilter filter = new SelectionFilter(filterList); ed.WriteMessage("\n请选择文本对象,或按ESC取消...\n"); PromptSelectionResult selRes = ed.GetSelection(selOpts, filter); if (selRes.Status == PromptStatus.Cancel) { ed.WriteMessage("操作已取消。\n"); return; } if (selRes.Status != PromptStatus.OK) { ed.WriteMessage("未选择任何对象。\n"); return; } if (selRes.Value.Count == 0) { MessageBox.Show("没有选择任何文本对象!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } ed.WriteMessage($"已选择 {selRes.Value.Count} 个对象,正在提取文本...\n"); string textContent = ExtractTextFromSelection(doc, selRes.Value); if (string.IsNullOrEmpty(textContent)) { MessageBox.Show("选中的对象中没有可提取的文本!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } using (InputTextNameForm inputForm = new InputTextNameForm()) { if (inputForm.ShowDialog() == DialogResult.OK && !string.IsNullOrEmpty(inputForm.TextName)) { string textName = inputForm.TextName.Trim(); if (string.IsNullOrEmpty(textName)) { MessageBox.Show("文本名称不能为空!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } textName = CleanTextName(textName); string filePath = Path.Combine(_userTextsPath, $"{textName}.txt"); if (File.Exists(filePath)) { if (MessageBox.Show($"文本 '{textName}' 已存在,是否覆盖?", "确认覆盖", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return; } } File.WriteAllText(filePath, textContent); LoadAllTexts(); ed.WriteMessage($"\n文本 '{textName}' 已成功入库!"); MessageBox.Show($"文本 '{textName}' 已成功入库!", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } catch (SystemException ex) { MessageBox.Show($"保存文本时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private string ExtractTextFromSelection(Document doc, SelectionSet selectionSet) { List<string> textContents = new List<string>(); int textCount = 0; int mtextCount = 0; int otherCount = 0; using (Transaction tr = doc.Database.TransactionManager.StartTransaction()) { foreach (ObjectId id in selectionSet.GetObjectIds()) { DBObject obj = tr.GetObject(id, OpenMode.ForRead); if (obj is DBText dbText) { textContents.Add(dbText.TextString); textCount++; } else if (obj is MText mText) { textContents.Add(mText.Contents); mtextCount++; } else { otherCount++; } } tr.Commit(); } System.Diagnostics.Debug.WriteLine($"提取文本统计 - TEXT: {textCount}, MTEXT: {mtextCount}, 其他: {otherCount}"); return string.Join(Environment.NewLine, textContents); } private string CleanTextName(string name) { char[] invalidChars = Path.GetInvalidFileNameChars(); return string.Join("_", name.Split(invalidChars, StringSplitOptions.RemoveEmptyEntries)); } private void btnDelete_Click(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(_selectedTextName) || _isSystemText) { MessageBox.Show("请选择一个用户文本进行删除!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (MessageBox.Show($"确定要删除文本 '{_selectedTextName}' 吗?", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { if (File.Exists(_selectedTextPath)) { File.Delete(_selectedTextPath); LoadAllTexts(); ClearPreview(); MessageBox.Show("文本已成功删除!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("文本文件不存在!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } catch (SystemException ex) { MessageBox.Show($"删除文本时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnInsert_Click(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(_selectedTextName) || string.IsNullOrEmpty(_selectedTextPath)) { MessageBox.Show("请先选择一个文本!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } Document doc = AcadApp.DocumentManager.MdiActiveDocument; if (doc == null) { MessageBox.Show("没有打开的AutoCAD文档!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } using (DocumentLock docLock = doc.LockDocument()) { Editor ed = doc.Editor; PromptPointOptions ptOpts = new PromptPointOptions("\n请指定插入点: "); PromptPointResult ptRes = ed.GetPoint(ptOpts); if (ptRes.Status != PromptStatus.OK) return; Point3d insertPoint = ptRes.Value; string textToInsert = textBoxPreview.Text; if (InsertText(doc, insertPoint, textToInsert)) { ed.WriteMessage($"\n文本 '{_selectedTextName}' 已成功插入!"); textBoxPreview.Text = _originalPreviewContent; } else { MessageBox.Show($"文本 '{_selectedTextName}' 插入失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } catch (SystemException ex) { MessageBox.Show($"插入文本时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private bool InsertText(Document doc, Point3d insertPoint, string textContent) { try { using (Transaction tr = doc.Database.TransactionManager.StartTransaction()) { BlockTable bt = tr.GetObject(doc.Database.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; MText mText = new MText(); mText.Contents = textContent; mText.Location = insertPoint; mText.Width = 500; mText.Height = 2.5; btr.AppendEntity(mText); tr.AddNewlyCreatedDBObject(mText, true); tr.Commit(); return true; } } catch (SystemException ex) { System.Diagnostics.Debug.WriteLine($"插入文本失败: {ex.Message}"); return false; } } private void treeViewDirectory_AfterSelect(object sender, TreeViewEventArgs e) { try { if (e.Node.Tag is TextInfo textInfo) { _selectedTextName = textInfo.Name; _selectedTextPath = textInfo.Path; _isSystemText = textInfo.IsSystemText; // 显示文本内容并确保滚动到顶部 textBoxPreview.Text = textInfo.Content; textBoxPreview.SelectionStart = 0; textBoxPreview.SelectionLength = 0; textBoxPreview.ScrollToCaret(); // 滚动到光标位置(顶部) _originalPreviewContent = textInfo.Content; labelPreviewInfo.Text = $"预览: {textInfo.Name}"; btnDelete.Enabled = !textInfo.IsSystemText; } else { ClearPreview(); btnDelete.Enabled = false; _selectedTextName = string.Empty; _selectedTextPath = string.Empty; } } catch (SystemException ex) { MessageBox.Show($"选择文本时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void ClearPreview() { textBoxPreview.Text = string.Empty; _originalPreviewContent = string.Empty; labelPreviewInfo.Text = "预览: 无"; } private void btnRefresh_Click(object sender, EventArgs e) { try { LoadAllTexts(); ClearPreview(); } catch (SystemException ex) { MessageBox.Show($"刷新词库时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } public partial class InputTextNameForm : Form { public string TextName { get; private set; } public InputTextNameForm() { InitializeComponent(); } private void btnSave_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(textBoxTextName.Text)) { MessageBox.Show("请输入文本名称!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } TextName = textBoxTextName.Text.Trim(); DialogResult = DialogResult.OK; Close(); } private void btnCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } private void InputTextNameForm_Load(object sender, EventArgs e) { textBoxTextName.Focus(); } private void textBoxTextName_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Enter) btnSave_Click(sender, e); else if (e.KeyChar == (char)Keys.Escape) btnCancel_Click(sender, e); } } } namespace CadLibraryPlugin { partial class LibraryForm { private System.ComponentModel.IContainer components = null; protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { this.panelButtons = new System.Windows.Forms.Panel(); this.btnRefresh = new System.Windows.Forms.Button(); this.btnInsert = new System.Windows.Forms.Button(); this.btnDelete = new System.Windows.Forms.Button(); this.btnAdd = new System.Windows.Forms.Button(); this.splitContainerMain = new System.Windows.Forms.SplitContainer(); this.treeViewDirectory = new System.Windows.Forms.TreeView(); this.panelPreview = new System.Windows.Forms.Panel(); this.labelPreviewInfo = new System.Windows.Forms.Label(); this.textBoxPreview = new System.Windows.Forms.TextBox(); this.panelButtons.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainerMain)).BeginInit(); this.splitContainerMain.Panel1.SuspendLayout(); this.splitContainerMain.Panel2.SuspendLayout(); this.splitContainerMain.SuspendLayout(); this.panelPreview.SuspendLayout(); this.SuspendLayout(); // // panelButtons // this.panelButtons.Controls.Add(this.btnRefresh); this.panelButtons.Controls.Add(this.btnInsert); this.panelButtons.Controls.Add(this.btnDelete); this.panelButtons.Controls.Add(this.btnAdd); this.panelButtons.Dock = System.Windows.Forms.DockStyle.Top; this.panelButtons.Location = new System.Drawing.Point(0, 0); this.panelButtons.Margin = new System.Windows.Forms.Padding(0); this.panelButtons.Name = "panelButtons"; this.panelButtons.Size = new System.Drawing.Size(800, 45); this.panelButtons.TabIndex = 0; // // btnRefresh // this.btnRefresh.Location = new System.Drawing.Point(340, 8); this.btnRefresh.Name = "btnRefresh"; this.btnRefresh.Size = new System.Drawing.Size(75, 30); this.btnRefresh.TabIndex = 3; this.btnRefresh.Text = "刷新"; this.btnRefresh.UseVisualStyleBackColor = true; this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click); // // btnInsert // this.btnInsert.Location = new System.Drawing.Point(250, 8); this.btnInsert.Name = "btnInsert"; this.btnInsert.Size = new System.Drawing.Size(75, 30); this.btnInsert.TabIndex = 2; this.btnInsert.Text = "选用"; this.btnInsert.UseVisualStyleBackColor = true; this.btnInsert.Click += new System.EventHandler(this.btnInsert_Click); // // btnDelete // this.btnDelete.Location = new System.Drawing.Point(160, 8); this.btnDelete.Name = "btnDelete"; this.btnDelete.Size = new System.Drawing.Size(75, 30); this.btnDelete.TabIndex = 1; this.btnDelete.Text = "删除"; this.btnDelete.UseVisualStyleBackColor = true; this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // btnAdd // this.btnAdd.Location = new System.Drawing.Point(10, 8); this.btnAdd.Name = "btnAdd"; this.btnAdd.Size = new System.Drawing.Size(135, 30); this.btnAdd.TabIndex = 0; this.btnAdd.Text = "拾取文本入库"; this.btnAdd.UseVisualStyleBackColor = true; this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // splitContainerMain // this.splitContainerMain.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainerMain.Location = new System.Drawing.Point(0, 45); this.splitContainerMain.Name = "splitContainerMain"; // 调整分割容器比例,给预览窗口更多空间 this.splitContainerMain.SplitterDistance = 220; // // splitContainerMain.Panel1 // this.splitContainerMain.Panel1.Controls.Add(this.treeViewDirectory); // // splitContainerMain.Panel2 // this.splitContainerMain.Panel2.Controls.Add(this.panelPreview); this.splitContainerMain.Size = new System.Drawing.Size(800, 405); // 减小总高度 this.splitContainerMain.SplitterWidth = 6; this.splitContainerMain.TabIndex = 1; // // treeViewDirectory // this.treeViewDirectory.Dock = System.Windows.Forms.DockStyle.Fill; this.treeViewDirectory.Location = new System.Drawing.Point(0, 0); this.treeViewDirectory.Name = "treeViewDirectory"; this.treeViewDirectory.Size = new System.Drawing.Size(220, 405); this.treeViewDirectory.TabIndex = 0; this.treeViewDirectory.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeViewDirectory_AfterSelect); // // panelPreview // this.panelPreview.Controls.Add(this.labelPreviewInfo); this.panelPreview.Controls.Add(this.textBoxPreview); this.panelPreview.Dock = System.Windows.Forms.DockStyle.Fill; this.panelPreview.Location = new System.Drawing.Point(0, 0); this.panelPreview.Margin = new System.Windows.Forms.Padding(0); this.panelPreview.Name = "panelPreview"; this.panelPreview.Padding = new System.Windows.Forms.Padding(5); this.panelPreview.Size = new System.Drawing.Size(574, 405); this.panelPreview.TabIndex = 0; // // labelPreviewInfo // this.labelPreviewInfo.Dock = System.Windows.Forms.DockStyle.Top; this.labelPreviewInfo.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.labelPreviewInfo.Location = new System.Drawing.Point(5, 5); this.labelPreviewInfo.Margin = new System.Windows.Forms.Padding(0, 0, 0, 5); this.labelPreviewInfo.Name = "labelPreviewInfo"; this.labelPreviewInfo.Size = new System.Drawing.Size(564, 25); // 增加标签高度 this.labelPreviewInfo.TabIndex = 1; this.labelPreviewInfo.Text = "预览: 无"; this.labelPreviewInfo.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // textBoxPreview // this.textBoxPreview.Dock = System.Windows.Forms.DockStyle.Fill; this.textBoxPreview.Location = new System.Drawing.Point(5, 35); // 增加顶部距离,避免文本被遮挡 this.textBoxPreview.Margin = new System.Windows.Forms.Padding(10, 5, 10, 10); // 增加边距 this.textBoxPreview.Multiline = true; this.textBoxPreview.Name = "textBoxPreview"; this.textBoxPreview.Padding = new System.Windows.Forms.Padding(8); this.textBoxPreview.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.textBoxPreview.Size = new System.Drawing.Size(564, 365); // 调整高度 this.textBoxPreview.TabIndex = 0; this.textBoxPreview.WordWrap = true; // // LibraryForm // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.ClientSize = new System.Drawing.Size(800, 450); // 减小窗体高度 this.Controls.Add(this.splitContainerMain); this.Controls.Add(this.panelButtons); this.MinimumSize = new System.Drawing.Size(800, 450); this.Name = "LibraryForm"; this.Text = "通用词库"; this.panelButtons.ResumeLayout(false); this.splitContainerMain.Panel1.ResumeLayout(false); this.splitContainerMain.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainerMain)).EndInit(); this.splitContainerMain.ResumeLayout(false); this.panelPreview.ResumeLayout(false); this.panelPreview.PerformLayout(); this.ResumeLayout(false); } private System.Windows.Forms.Panel panelButtons; internal System.Windows.Forms.Button btnAdd; internal System.Windows.Forms.Button btnDelete; internal System.Windows.Forms.Button btnInsert; internal System.Windows.Forms.Button btnRefresh; private System.Windows.Forms.SplitContainer splitContainerMain; internal System.Windows.Forms.TreeView treeViewDirectory; private System.Windows.Forms.Panel panelPreview; internal System.Windows.Forms.TextBox textBoxPreview; internal System.Windows.Forms.Label labelPreviewInfo; } partial class InputTextNameForm { private System.ComponentModel.IContainer components = null; protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.textBoxTextName = new System.Windows.Forms.TextBox(); this.btnSave = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(20, 20); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(35, 12); this.label1.TabIndex = 0; this.label1.Text = "词名:"; // // textBoxTextName // this.textBoxTextName.Location = new System.Drawing.Point(60, 17); this.textBoxTextName.Name = "textBoxTextName"; this.textBoxTextName.Size = new System.Drawing.Size(200, 21); this.textBoxTextName.TabIndex = 1; this.textBoxTextName.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBoxTextName_KeyPress); // // btnSave // this.btnSave.Location = new System.Drawing.Point(60, 60); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(75, 23); this.btnSave.TabIndex = 2; this.btnSave.Text = "保存"; this.btnSave.UseVisualStyleBackColor = true; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // btnCancel // this.btnCancel.Location = new System.Drawing.Point(185, 60); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(75, 23); this.btnCancel.TabIndex = 3; this.btnCancel.Text = "取消"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // InputTextNameForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(300, 100); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnSave); this.Controls.Add(this.textBoxTextName); this.Controls.Add(this.label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "InputTextNameForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "保存文本"; this.Load += new System.EventHandler(this.InputTextNameForm_Load); this.ResumeLayout(false); this.PerformLayout(); } private System.Windows.Forms.Label label1; internal System.Windows.Forms.TextBox textBoxTextName; internal System.Windows.Forms.Button btnSave; internal System.Windows.Forms.Button btnCancel; } } 预览窗口内的内容还是显示不完整;举例:选择目录中的“1.结构梁做法”,预览窗口中显示的内容: 40x90木方次龙骨@100 50x100x3单根方钢主龙骨 10#双槽钢拖梁支撑 预览窗口中必须显示的内容是: 200x500结构梁 15厚模板 40x90木方次龙骨@100 50x100x3单根方钢主龙骨 10#双槽钢拖梁支撑
09-27
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Display; namespace WaterPipelineGIS2 { public partial class main : Form { private IFeatureLayer _selectedFeatureLayer; private System.Drawing.Point _lastRightClickPosition; private SelectionMode currentMode = SelectionMode.None; private IGraphicsContainer _spatialSelectionGraphics; private IGraphicsContainer _attributeHighlightGraphics; private ToolStripStatusLabel lblStatus; // 添加量测模式枚举 public enum MeasureMode { None, PolygonArea, PolygonPerimeter, PolylineLength, PointCoordinate } // 添加量测相关变量 private MeasureMode currentMeasureMode = MeasureMode.None; private List<IPoint> measurePoints = new List<IPoint>(); private IElement tempMeasureElement; private List<IElement> measurementElements = new List<IElement>(); private bool isMeasuring = false; // 修改后的SelectionMode枚举 public enum SelectionMode { None, Rectangle, Circle, Polygon, Polyline } private void InitializeGraphicsContainers() { try { // 确保地图控件已初始化 if (axMapControl1 == null) return; // 确保ActiveView已初始化 if (axMapControl1.ActiveView == null) { // 尝试刷新视图 axMapControl1.ActiveView.Refresh(); } if (axMapControl1.ActiveView != null) { _spatialSelectionGraphics = axMapControl1.ActiveView.GraphicsContainer; _attributeHighlightGraphics = axMapControl1.ActiveView.GraphicsContainer; } } catch (Exception ex) { MessageBox.Show("初始化图形容器失败: " + ex.Message); } } private void Form1_Load(object sender, EventArgs e) { // 强制创建地图控件 if (!axMapControl1.Created) axMapControl1.CreateControl(); // 延迟初始化图形容器 axMapControl1.ActiveView.Refresh(); InitializeGraphicsContainers(); } public main() { InitializeComponent(); // 确保设计器初始化完成 if (statusStrip1 != null) { lblStatus = new ToolStripStatusLabel(); statusStrip1.Items.Add(lblStatus); lblStatus.Text = "就绪"; } // 添加窗体加载事件处理程序 this.Load += Form1_LoadHandler; // === 修改结束 === // 事件绑定保持不变 axMapControl1.OnMouseMove += axMapControl1_OnMouseMove; axMapControl1.OnMouseDown += axMapControl1_OnMouseDown; axMapControl1.OnDoubleClick += new IMapControlEvents2_Ax_OnDoubleClickEventHandler(axMapControl1_OnDoubleClick); } // === 新增方法 === private void Form1_LoadHandler(object sender, EventArgs e) { // 确保地图控件已创建 if (axMapControl1 != null && !axMapControl1.Created) { axMapControl1.CreateControl(); } // 初始化图形容器 InitializeGraphicsContainers(); // 确保 ActiveView 有效 if (axMapControl1.ActiveView != null) { // 刷新视图以确保图形容器可用 axMapControl1.ActiveView.Refresh(); } } private void axMapControl1_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e) { try { // 公共坐标显示 double mapX = e.mapX; double mapY = e.mapY; lblCoordinate.Text = "X: {mapX:F3} Y: {mapY:F3}"; // 量测模式预览 if (isMeasuring && measurePoints.Count > 0) { switch (currentMeasureMode) { case MeasureMode.PolygonArea: case MeasureMode.PolygonPerimeter: DrawTempPolygonMeasure(e.x, e.y); break; case MeasureMode.PolylineLength: DrawTempPolylineMeasure(e.x, e.y); break; } } } catch (Exception ex) { Console.WriteLine("鼠标移动错误: " + ex.Message); } } private void toolStripMenuItem2_Click(object sender, EventArgs e) { using (var rotateForm = new RotateForm()) { if (rotateForm.ShowDialog() == DialogResult.OK) { try { axMapControl1.Rotation = rotateForm.RotationAngle; axMapControl1.ActiveView.Refresh(); lblCoordinate.Text += " 旋转角度:" + rotateForm.RotationAngle + "°"; } catch (Exception ex) { MessageBox.Show("旋转失败:" + ex.Message); } } } } private void axTOCControl1_OnMouseDown(object sender, ITOCControlEvents_OnMouseDownEvent e) { if (e.button == 2) // 右键 { _lastRightClickPosition = new System.Drawing.Point(e.x, e.y); ITOCControl2 tocControl = (ITOCControl2)axTOCControl1.Object; IBasicMap basicMap = null; ILayer layer = null; object other = Type.Missing; object index = Type.Missing; esriTOCControlItem itemType = esriTOCControlItem.esriTOCControlItemNone; tocControl.HitTest(e.x, e.y, ref itemType, ref basicMap, ref layer, ref other, ref index); if (itemType == esriTOCControlItem.esriTOCControlItemLayer && layer != null) { contextMenuStripTOC.Show(axTOCControl1, e.x, e.y); } } } private void openAttributeTableToolStripMenuItem_Click(object sender, EventArgs e) { ITOCControl2 tocControl = (ITOCControl2)axTOCControl1.Object; IBasicMap basicMap = null; ILayer layer = null; object other = Type.Missing; object index = Type.Missing; esriTOCControlItem itemType = esriTOCControlItem.esriTOCControlItemNone; System.Drawing.Point screenPos = contextMenuStripTOC.PointToClient(Control.MousePosition); System.Drawing.Point controlPos = axTOCControl1.PointToClient(Control.MousePosition); tocControl.HitTest( controlPos.X, controlPos.Y, ref itemType, ref basicMap, ref layer, ref other, ref index ); IFeatureLayer featureLayer = layer as IFeatureLayer; if (featureLayer != null) { _selectedFeatureLayer = featureLayer; AttributeTableForm attrForm = new AttributeTableForm( _selectedFeatureLayer, this ); attrForm.Show(); } } private void SetSelectionSymbol() { ISimpleFillSymbol fillSymbol = new SimpleFillSymbolClass(); fillSymbol.Color = GetRgbColor(255, 0, 0); fillSymbol.Style = esriSimpleFillStyle.esriSFSSolid; ISimpleLineSymbol lineSymbol = new SimpleLineSymbolClass(); lineSymbol.Color = GetRgbColor(255, 255, 0); lineSymbol.Width = 2; fillSymbol.Outline = lineSymbol; if (_selectedFeatureLayer != null) { IGeoFeatureLayer geoLayer = (IGeoFeatureLayer)_selectedFeatureLayer; ISimpleRenderer renderer = new SimpleRendererClass(); renderer.Symbol = (ISymbol)fillSymbol; geoLayer.Renderer = (IFeatureRenderer)renderer; axMapControl1.ActiveView.Refresh(); } } private IRgbColor GetRgbColor(int r, int g, int b) { IRgbColor color = new RgbColorClass(); color.Red = r; color.Green = g; color.Blue = b; return color; } private IRgbColor GetRgbColor(int r, int g, int b, int alpha) { IRgbColor color = new RgbColorClass(); color.Red = r; color.Green = g; color.Blue = b; color.Transparency = (byte)(255 - alpha); return color; } public void ActivateFeatureLayer(IFeatureLayer featureLayer) { if (featureLayer == null) return; _selectedFeatureLayer = featureLayer; axMapControl1.ActiveView.Refresh(); axTOCControl1.Update(); } public void HighlightAndZoomToFeature(IFeatureLayer featureLayer, int oid) { try { if (featureLayer == null || featureLayer.FeatureClass == null) { MessageBox.Show("图层或要素类无效!"); return; } IFeature feature = featureLayer.FeatureClass.GetFeature(oid); if (feature == null || feature.Shape == null) { MessageBox.Show("要素 OID " + oid + " 不存在或无几何!"); return; } IGeometry geometry = feature.Shape; IEnvelope envelope = geometry.Envelope; if (envelope.IsEmpty || envelope.Width == 0 || envelope.Height == 0) { envelope.Expand(10, 10, true); } else { envelope.Expand(1.5, 1.5, true); } axMapControl1.Extent = envelope; axMapControl1.ActiveView.ScreenDisplay.UpdateWindow(); HighlightGeometry(geometry); } catch (Exception ex) { MessageBox.Show("高亮要素失败: " + ex.Message); } } private void btnRectSelect_Click(object sender, EventArgs e) { currentMeasureMode = MeasureMode.None; // 互斥 currentMode = SelectionMode.Rectangle; axMapControl1.CurrentTool = null; axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair; lblStatus.Text = "矩形选择模式"; } private void btnCircleSelect_Click(object sender, EventArgs e) { currentMeasureMode = MeasureMode.None; // 互斥 currentMode = SelectionMode.Circle; axMapControl1.CurrentTool = null; axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair; lblStatus.Text = "圆形选择模式"; } private void btnPolygonSelect_Click(object sender, EventArgs e) { currentMeasureMode = MeasureMode.None; // 互斥 currentMode = SelectionMode.Polygon; axMapControl1.CurrentTool = null; axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair; lblStatus.Text = "多边形选择模式"; } private void btnLineSelect_Click(object sender, EventArgs e) { currentMeasureMode = MeasureMode.None; // 互斥 currentMode = SelectionMode.Polyline; axMapControl1.CurrentTool = null; axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair; lblStatus.Text = "折线选择模式"; } private void axMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e) { try { // 量测模式处理 if (isMeasuring) { HandleMeasureMode(e); return; } // 左键点击 if (e.button == 1) { if (currentMode != SelectionMode.None) { HandleSpatialSelection(e); } } } catch (Exception ex) { MessageBox.Show("操作错误: " + ex.Message); } } private void PerformSpatialSelection(IGeometry geometry) { try { IMap map = axMapControl1.Map; if (map == null) return; map.ClearSelection(); for (int i = 0; i < map.LayerCount; i++) { IFeatureLayer featureLayer = map.get_Layer(i) as IFeatureLayer; if (featureLayer == null || !featureLayer.Valid || featureLayer.FeatureClass == null) continue; ISpatialFilter filter = new SpatialFilterClass(); filter.Geometry = geometry; filter.GeometryField = featureLayer.FeatureClass.ShapeFieldName; filter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; IFeatureSelection selection = (IFeatureSelection)featureLayer; selection.SelectFeatures(filter, esriSelectionResultEnum.esriSelectionResultNew, false); } axMapControl1.Refresh(esriViewDrawPhase.esriViewGeoSelection, null, null); axMapControl1.ActiveView.Refresh(); } catch (Exception ex) { MessageBox.Show("空间查询失败: " + ex.Message); } } private void HighlightGeometry(IGeometry geometry) { try { if (_spatialSelectionGraphics != null) { _spatialSelectionGraphics.DeleteAllElements(); } IElement element = null; switch (geometry.GeometryType) { case esriGeometryType.esriGeometryPolygon: { ISimpleFillSymbol fillSymbol = new SimpleFillSymbolClass(); fillSymbol.Color = GetRgbColor(255, 0, 0, 80); ISimpleLineSymbol outline = new SimpleLineSymbolClass(); outline.Color = GetRgbColor(255, 0, 0); outline.Width = 2; fillSymbol.Outline = outline; element = new PolygonElementClass(); element.Geometry = geometry; ((IFillShapeElement)element).Symbol = fillSymbol; } break; case esriGeometryType.esriGeometryPolyline: { ISimpleLineSymbol lineSymbol = new SimpleLineSymbolClass(); lineSymbol.Color = GetRgbColor(255, 0, 0); lineSymbol.Width = 3; element = new LineElementClass(); element.Geometry = geometry; ((ILineElement)element).Symbol = lineSymbol; } break; case esriGeometryType.esriGeometryPoint: { ISimpleMarkerSymbol markerSymbol = new SimpleMarkerSymbolClass(); markerSymbol.Color = GetRgbColor(255, 0, 0); markerSymbol.Size = 12; element = new MarkerElementClass(); element.Geometry = geometry; ((IMarkerElement)element).Symbol = markerSymbol; } break; } if (element != null && _spatialSelectionGraphics != null) { _spatialSelectionGraphics.AddElement(element, 0); axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); } } catch (Exception ex) { MessageBox.Show("高亮显示失败: " + ex.Message); } } private void btnClearSelection_Click(object sender, EventArgs e) { try { if (axMapControl1.Map != null) { axMapControl1.Map.ClearSelection(); } if (_spatialSelectionGraphics != null) { _spatialSelectionGraphics.DeleteAllElements(); } axMapControl1.ActiveView.PartialRefresh( esriViewDrawPhase.esriViewGeoSelection | esriViewDrawPhase.esriViewGraphics, null, null ); axMapControl1.ActiveView.Refresh(); currentMode = SelectionMode.None; axMapControl1.MousePointer = esriControlsMousePointer.esriPointerDefault; lblStatus.Text = "就绪"; } catch (Exception ex) { MessageBox.Show("清除选择失败: " + ex.Message); } } private void axMapControl1_OnDoubleClick(object sender, IMapControlEvents2_OnDoubleClickEvent e) { if (currentMode != SelectionMode.None) { currentMode = SelectionMode.None; axMapControl1.CurrentTool = null; axMapControl1.MousePointer = esriControlsMousePointer.esriPointerDefault; lblStatus.Text = "就绪"; } } private void HandleSpatialSelection(IMapControlEvents2_OnMouseDownEvent e) { IGeometry geometry = null; switch (currentMode) { case SelectionMode.Rectangle: IEnvelope rectEnv = axMapControl1.TrackRectangle(); if (rectEnv != null) { IPolygon polygon = new PolygonClass(); polygon.SpatialReference = axMapControl1.SpatialReference; ISegmentCollection segColl = (ISegmentCollection)polygon; segColl.SetRectangle(rectEnv); geometry = (IGeometry)polygon; } break; case SelectionMode.Circle: IEnvelope envelope = axMapControl1.TrackRectangle(); if (envelope.Width <= 0 || envelope.Height <= 0) { MessageBox.Show("请拖拽有效的矩形范围以创建圆形!"); return; } IPoint center = new PointClass(); center.PutCoords( (envelope.XMin + envelope.XMax) / 2, (envelope.YMin + envelope.YMax) / 2 ); double radius = Math.Max(envelope.Width, envelope.Height) / 2; ICircularArc circularArc = new CircularArcClass(); IConstructCircularArc constructArc = (IConstructCircularArc)circularArc; constructArc.ConstructCircle(center, radius, true); ISegmentCollection circleSegColl = new PolygonClass(); circleSegColl.AddSegment((ISegment)circularArc); geometry = (IGeometry)circleSegColl; geometry.SpatialReference = axMapControl1.SpatialReference; break; case SelectionMode.Polygon: geometry = axMapControl1.TrackPolygon(); break; case SelectionMode.Polyline: geometry = axMapControl1.TrackLine(); break; } if (geometry != null) { PerformSpatialSelection(geometry); HighlightGeometry(geometry); } } // 创建折线几何 private IPolyline CreatePolyline(List<IPoint> points, IPoint currentPoint = null) { try { // 创建点集合 IPointCollection pointCollection = new PolylineClass(); // 添加所有点 foreach (IPoint point in points) { if (point != null) { pointCollection.AddPoint(point); } } // 添加当前鼠标位置 if (currentPoint != null) { pointCollection.AddPoint(currentPoint); } // 转换为折线 IPolyline polyline = pointCollection as IPolyline; if (polyline == null) return null; // 设置空间参考(关键!) if (axMapControl1.SpatialReference != null) { polyline.SpatialReference = axMapControl1.SpatialReference; } // 简化几何 ITopologicalOperator topoOp = polyline as ITopologicalOperator; if (topoOp != null) { topoOp.Simplify(); } return polyline; } catch (Exception ex) { MessageBox.Show("创建折线时出错: " + ex.Message); return null; } } // 创建多边形几何 private IPolygon CreatePolygon(List<IPoint> points, IPoint currentPoint = null) { try { // 创建点集合 IPointCollection pointCollection = new PolygonClass(); // 添加所有点 foreach (IPoint point in points) { if (point != null) { pointCollection.AddPoint(point); } } // 添加当前鼠标位置 if (currentPoint != null) { pointCollection.AddPoint(currentPoint); } // 转换为多边形 IPolygon polygon = pointCollection as IPolygon; if (polygon == null) return null; // 设置空间参考(关键!) if (axMapControl1.SpatialReference != null) { polygon.SpatialReference = axMapControl1.SpatialReference; } // 简化几何 ITopologicalOperator topoOp = polygon as ITopologicalOperator; if (topoOp != null) { topoOp.Simplify(); } return polygon; } catch (Exception ex) { MessageBox.Show("创建多边形时出错: " + ex.Message); return null; } } // 量测菜单项点击事件处理 private void 面积量测ToolStripMenuItem_Click(object sender, EventArgs e) { StartMeasureMode(MeasureMode.PolygonArea); } private void 周长量测ToolStripMenuItem_Click(object sender, EventArgs e) { StartMeasureMode(MeasureMode.PolygonPerimeter); } private void 折线周长量测ToolStripMenuItem_Click(object sender, EventArgs e) { StartMeasureMode(MeasureMode.PolylineLength); } private void 点坐标量测ToolStripMenuItem_Click(object sender, EventArgs e) { StartMeasureMode(MeasureMode.PointCoordinate); } // 开始量测模式 private void StartMeasureMode(MeasureMode mode) { currentMode = SelectionMode.None; // 互斥 // 清除之前的状态 EndMeasureMode(); currentMeasureMode = mode; isMeasuring = true; measurePoints.Clear(); // 设置鼠标指针 axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair; // 设置状态栏提示 switch (mode) { case MeasureMode.PolygonArea: lblStatus.Text = "面积量测: 左键添加顶点,右键完成"; break; case MeasureMode.PolygonPerimeter: lblStatus.Text = "周长量测: 左键添加顶点,右键完成"; break; case MeasureMode.PolylineLength: lblStatus.Text = "长度量测: 左键添加顶点,右键完成"; break; case MeasureMode.PointCoordinate: lblStatus.Text = "点坐标量测: 左键点击地图获取坐标"; break; } } // 结束量测模式 private void EndMeasureMode() { ClearTempMeasureElement(); measurePoints.Clear(); isMeasuring = false; currentMeasureMode = MeasureMode.None; axMapControl1.MousePointer = esriControlsMousePointer.esriPointerDefault; lblStatus.Text = "就绪"; } // 绘制临时多边形量测图形 private void DrawTempPolygonMeasure(int x, int y) { if (measurePoints.Count == 0) return; try { // 清除之前的临时图形 ClearTempMeasureElement(); // 获取当前鼠标位置 IPoint currentPoint = axMapControl1.ToMapPoint(x, y); // 创建临时多边形(包括当前鼠标位置) IPolygon polygon = CreatePolygon(measurePoints, currentPoint); // 创建符号(蓝色边框,半透明填充) ISimpleLineSymbol lineSymbol = new SimpleLineSymbolClass(); lineSymbol.Color = GetRgbColor(0, 0, 255); // 蓝色 lineSymbol.Width = 2; ISimpleFillSymbol fillSymbol = new SimpleFillSymbolClass(); fillSymbol.Outline = lineSymbol; fillSymbol.Color = GetRgbColor(0, 255, 255, 100); // 青色半透明 // 创建元素 tempMeasureElement = new PolygonElementClass(); tempMeasureElement.Geometry = polygon; ((IFillShapeElement)tempMeasureElement).Symbol = fillSymbol; // 添加到地图 IGraphicsContainer graphics = axMapControl1.Map as IGraphicsContainer; if (graphics != null) { graphics.AddElement(tempMeasureElement, 0); axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); } } catch (Exception ex) { Console.WriteLine("量测预览错误: " + ex.Message); } } // 绘制临时折线量测图形 private void DrawTempPolylineMeasure(int x, int y) { if (measurePoints.Count == 0) return; try { // 清除之前的临时图形 ClearTempMeasureElement(); // 获取当前鼠标位置 IPoint currentPoint = axMapControl1.ToMapPoint(x, y); // 创建临时折线(包括当前鼠标位置) IPolyline polyline = CreatePolyline(measurePoints, currentPoint); // 创建符号(红色粗线) ISimpleLineSymbol lineSymbol = new SimpleLineSymbolClass(); lineSymbol.Color = GetRgbColor(255, 0, 0); // 红色 lineSymbol.Width = 3; // 创建元素 tempMeasureElement = new LineElementClass(); tempMeasureElement.Geometry = polyline; ((ILineElement)tempMeasureElement).Symbol = lineSymbol; // 添加到地图 IGraphicsContainer graphics = axMapControl1.Map as IGraphicsContainer; if (graphics != null) { graphics.AddElement(tempMeasureElement, 0); axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); } } catch (Exception ex) { Console.WriteLine("量测预览错误: " + ex.Message); } } // 清除临时量测图形 private void ClearTempMeasureElement() { if (tempMeasureElement != null) { IGraphicsContainer graphics = axMapControl1.Map as IGraphicsContainer; if (graphics != null) { graphics.DeleteElement(tempMeasureElement); axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); } tempMeasureElement = null; } } // 处理量测模式 private void HandleMeasureMode(IMapControlEvents2_OnMouseDownEvent e) { try { // 获取当前鼠标位置 IPoint point = axMapControl1.ToMapPoint(e.x, e.y); // 左键添加点 if (e.button == 1) { switch (currentMeasureMode) { case MeasureMode.PolygonArea: case MeasureMode.PolygonPerimeter: case MeasureMode.PolylineLength: measurePoints.Add(point); break; case MeasureMode.PointCoordinate: CompletePointMeasure(point); break; } } // 右键完成量测 else if (e.button == 2) { switch (currentMeasureMode) { case MeasureMode.PolygonArea: CompletePolygonMeasure(true); break; case MeasureMode.PolygonPerimeter: CompletePolygonMeasure(false); break; case MeasureMode.PolylineLength: CompletePolylineMeasure(); break; } } } catch (Exception ex) { MessageBox.Show("量测错误: " + ex.Message); } } // 完成多边形量测 private void CompletePolygonMeasure(bool isArea) { if (measurePoints.Count < 3) { MessageBox.Show("多边形至少需要3个顶点"); return; } try { // 创建最终多边形 IPolygon polygon = CreatePolygon(measurePoints); if (polygon == null || polygon.IsEmpty) { MessageBox.Show("无法创建有效多边形"); return; } // 计算量测结果 IArea area = polygon as IArea; double result = 0; string unit = ""; string title = ""; if (isArea) { // 面积量测 result = area.Area; // 平方米 unit = "平方米"; title = "面积量测结果"; } else { // 周长量测 ICurve curve = polygon as ICurve; result = curve.Length; // 米 unit = "米"; title = "周长量测结果"; } // 构建结果消息 string message = string.Format("{0:0.##} {1}", result, unit); if (isArea) { double hectareArea = result / 10000; // 公顷 message += string.Format("\n{0:0.##} 公顷", hectareArea); } else { double kilometer = result / 1000; // 千米 message += string.Format("\n{0:0.##} 千米", kilometer); } // 使用自定义窗体显示结果 ShowMeasureResult(title, message); // 绘制最终量测图形 DrawFinalMeasureElement(polygon, isArea); } catch (Exception ex) { MessageBox.Show("量测出错: " + ex.Message); } finally { // 结束量测模式 EndMeasureMode(); } } // 完成折线量测 private void CompletePolylineMeasure() { if (measurePoints.Count < 2) { MessageBox.Show("折线至少需要2个顶点"); return; } try { // 创建最终折线 IPolyline polyline = CreatePolyline(measurePoints); if (polyline == null || polyline.IsEmpty) { MessageBox.Show("无法创建有效折线"); return; } // 计算长度 ICurve curve = polyline as ICurve; double length = curve.Length; // 米 double kilometer = length / 1000; // 千米 // 构建结果消息 string message = string.Format("{0:0.##} 米\n{1:0.##} 千米", length, kilometer); // 使用自定义窗体显示结果 ShowMeasureResult("长度量测结果", message); // 绘制最终量测图形 DrawFinalMeasureElement(polyline); } catch (Exception ex) { MessageBox.Show("量测出错: " + ex.Message); } finally { // 结束量测模式 EndMeasureMode(); } } // 完成点坐标量测 private void CompletePointMeasure(IPoint point) { try { // 获取坐标系信息 string coordSystem = "未知坐标系"; if (axMapControl1.SpatialReference != null) { coordSystem = axMapControl1.SpatialReference.Name; } // 构建结果消息 string message = string.Format("X: {0:0.###}\nY: {1:0.###}\n\n坐标系: {2}", point.X, point.Y, coordSystem); // 使用自定义窗体显示结果 ShowMeasureResult("坐标量测结果", message); // 绘制点标记 DrawPointMarker(point); } catch (Exception ex) { MessageBox.Show("量测出错: " + ex.Message); } finally { // 结束量测模式 EndMeasureMode(); } } // 绘制最终量测图形 private void DrawFinalMeasureElement(IGeometry geometry, bool isArea = true) { IGraphicsContainer graphics = axMapControl1.Map as IGraphicsContainer; if (graphics == null) return; IElement element = null; if (geometry is IPolygon) { // 创建符号(蓝色边框,半透明填充) ISimpleLineSymbol lineSymbol = new SimpleLineSymbolClass(); lineSymbol.Color = GetRgbColor(0, 0, 255); // 蓝色 lineSymbol.Width = 2; ISimpleFillSymbol fillSymbol = new SimpleFillSymbolClass(); fillSymbol.Outline = lineSymbol; fillSymbol.Color = GetRgbColor(0, 255, 255, 100); // 青色半透明 // 创建元素 element = new PolygonElementClass(); element.Geometry = geometry; ((IFillShapeElement)element).Symbol = fillSymbol; } else if (geometry is IPolyline) { // 创建符号(红色粗线) ISimpleLineSymbol lineSymbol = new SimpleLineSymbolClass(); lineSymbol.Color = GetRgbColor(255, 0, 0); // 红色 lineSymbol.Width = 3; // 创建元素 element = new LineElementClass(); element.Geometry = geometry; ((ILineElement)element).Symbol = lineSymbol; } if (element != null) { // 添加到地图 graphics.AddElement(element, 0); measurementElements.Add(element); axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); } } // 绘制点标记 private void DrawPointMarker(IPoint point) { IGraphicsContainer graphics = axMapControl1.Map as IGraphicsContainer; if (graphics == null) return; // 创建符号(绿色十字) ISimpleMarkerSymbol markerSymbol = new SimpleMarkerSymbolClass(); markerSymbol.Style = esriSimpleMarkerStyle.esriSMSCross; markerSymbol.Color = GetRgbColor(0, 255, 0); // 绿色 markerSymbol.Size = 12; markerSymbol.Outline = true; markerSymbol.OutlineColor = GetRgbColor(0, 0, 0); // 黑色边框 markerSymbol.OutlineSize = 1; // 创建元素 IMarkerElement markerElement = new MarkerElementClass(); markerElement.Symbol = markerSymbol; ((IElement)markerElement).Geometry = point; // 添加到地图 graphics.AddElement((IElement)markerElement, 0); measurementElements.Add((IElement)markerElement); axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); } // 清除已绘制图形 private void 清除已绘制图形ToolStripMenuItem_Click(object sender, EventArgs e) { ClearMeasurementGraphics(); } // 清除量测图形 private void ClearMeasurementGraphics() { try { IActiveView activeView = axMapControl1.ActiveView; IGraphicsContainer graphics = activeView.GraphicsContainer; if (graphics == null) return; // 删除所有量测图形元素 foreach (IElement element in measurementElements) { graphics.DeleteElement(element); } // 清空列表 measurementElements.Clear(); // 强制刷新地图视图 activeView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null); activeView.Refresh(); lblStatus.Text = "已清除所有量测图形"; } catch (Exception ex) { MessageBox.Show("清除图形时出错: " + ex.Message); } } // 在 Form1 类中添加新方法 private void ShowMeasureResult(string title, string message) { using (MeasureResultForm resultForm = new MeasureResultForm(title, message)) { resultForm.ShowDialog(this); } } } }namespace WaterPipelineGIS2 { partial class main { /// <summary> /// 必需的设计器变量。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 清理所有正在使用的资源。 /// </summary> /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows 窗体设计器生成的代码 /// <summary> /// 设计器支持所需的方法 - 不要 /// 使用代码编辑器修改此方法的内容。 /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(main)); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripMenuItem(); this.清除选择ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.空间量测ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.面积量测ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.周长量测ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.点坐标量测ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.清除已绘制图形ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.panel1 = new System.Windows.Forms.Panel(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.groupBoxEagleEye = new System.Windows.Forms.GroupBox(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.lblCoordinate = new System.Windows.Forms.ToolStripStatusLabel(); this.lblResult = new System.Windows.Forms.ToolStripStatusLabel(); this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl(); this.txtRotateAngle = new System.Windows.Forms.ToolStripTextBox(); this.contextMenuStripTOC = new System.Windows.Forms.ContextMenuStrip(this.components); this.openAttributeTableToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.axMapControl2 = new ESRI.ArcGIS.Controls.AxMapControl(); this.axTOCControl1 = new ESRI.ArcGIS.Controls.AxTOCControl(); this.axMapControl1 = new ESRI.ArcGIS.Controls.AxMapControl(); this.axToolbarControl1 = new ESRI.ArcGIS.Controls.AxToolbarControl(); this.折线周长量测ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); this.menuStrip1.SuspendLayout(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.groupBoxEagleEye.SuspendLayout(); this.statusStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit(); this.contextMenuStripTOC.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.axMapControl2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).BeginInit(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem1}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(1042, 32); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // toolStripMenuItem1 // this.toolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem2, this.toolStripMenuItem3, this.空间量测ToolStripMenuItem}); this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Size = new System.Drawing.Size(58, 28); this.toolStripMenuItem1.Text = "功能"; // // toolStripMenuItem2 // this.toolStripMenuItem2.Name = "toolStripMenuItem2"; this.toolStripMenuItem2.Size = new System.Drawing.Size(152, 28); this.toolStripMenuItem2.Text = "地图旋转"; this.toolStripMenuItem2.Click += new System.EventHandler(this.toolStripMenuItem2_Click); // // toolStripMenuItem3 // this.toolStripMenuItem3.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem4, this.toolStripMenuItem5, this.toolStripMenuItem6, this.toolStripMenuItem7, this.清除选择ToolStripMenuItem}); this.toolStripMenuItem3.Name = "toolStripMenuItem3"; this.toolStripMenuItem3.Size = new System.Drawing.Size(152, 28); this.toolStripMenuItem3.Text = "空间选择"; // // toolStripMenuItem4 // this.toolStripMenuItem4.Name = "toolStripMenuItem4"; this.toolStripMenuItem4.Size = new System.Drawing.Size(206, 28); this.toolStripMenuItem4.Text = "绘制矩形选择"; this.toolStripMenuItem4.Click += new System.EventHandler(this.btnRectSelect_Click); // // toolStripMenuItem5 // this.toolStripMenuItem5.Name = "toolStripMenuItem5"; this.toolStripMenuItem5.Size = new System.Drawing.Size(206, 28); this.toolStripMenuItem5.Text = "绘制圆形选择"; this.toolStripMenuItem5.Click += new System.EventHandler(this.btnCircleSelect_Click); // // toolStripMenuItem6 // this.toolStripMenuItem6.Name = "toolStripMenuItem6"; this.toolStripMenuItem6.Size = new System.Drawing.Size(206, 28); this.toolStripMenuItem6.Text = "绘制多边形选择"; this.toolStripMenuItem6.Click += new System.EventHandler(this.btnPolygonSelect_Click); // // toolStripMenuItem7 // this.toolStripMenuItem7.Name = "toolStripMenuItem7"; this.toolStripMenuItem7.Size = new System.Drawing.Size(206, 28); this.toolStripMenuItem7.Text = "绘制折线选择"; this.toolStripMenuItem7.Click += new System.EventHandler(this.btnLineSelect_Click); // // 清除选择ToolStripMenuItem // this.清除选择ToolStripMenuItem.Name = "清除选择ToolStripMenuItem"; this.清除选择ToolStripMenuItem.Size = new System.Drawing.Size(206, 28); this.清除选择ToolStripMenuItem.Text = "清除选择"; this.清除选择ToolStripMenuItem.Click += new System.EventHandler(this.btnClearSelection_Click); // // 空间量测ToolStripMenuItem // this.空间量测ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.面积量测ToolStripMenuItem, this.周长量测ToolStripMenuItem, this.折线周长量测ToolStripMenuItem, this.点坐标量测ToolStripMenuItem, this.清除已绘制图形ToolStripMenuItem}); this.空间量测ToolStripMenuItem.Name = "空间量测ToolStripMenuItem"; this.空间量测ToolStripMenuItem.Size = new System.Drawing.Size(152, 28); this.空间量测ToolStripMenuItem.Text = "空间量测"; // // 面积量测ToolStripMenuItem // this.面积量测ToolStripMenuItem.Name = "面积量测ToolStripMenuItem"; this.面积量测ToolStripMenuItem.Size = new System.Drawing.Size(206, 28); this.面积量测ToolStripMenuItem.Text = "面积量测"; this.面积量测ToolStripMenuItem.Click += new System.EventHandler(this.面积量测ToolStripMenuItem_Click); // // 周长量测ToolStripMenuItem // this.周长量测ToolStripMenuItem.Name = "周长量测ToolStripMenuItem"; this.周长量测ToolStripMenuItem.Size = new System.Drawing.Size(206, 28); this.周长量测ToolStripMenuItem.Text = "周长量测"; this.周长量测ToolStripMenuItem.Click += new System.EventHandler(this.周长量测ToolStripMenuItem_Click); // // 点坐标量测ToolStripMenuItem // this.点坐标量测ToolStripMenuItem.Name = "点坐标量测ToolStripMenuItem"; this.点坐标量测ToolStripMenuItem.Size = new System.Drawing.Size(206, 28); this.点坐标量测ToolStripMenuItem.Text = "点坐标量测"; this.点坐标量测ToolStripMenuItem.Click += new System.EventHandler(this.点坐标量测ToolStripMenuItem_Click); // // 清除已绘制图形ToolStripMenuItem // this.清除已绘制图形ToolStripMenuItem.Name = "清除已绘制图形ToolStripMenuItem"; this.清除已绘制图形ToolStripMenuItem.Size = new System.Drawing.Size(206, 28); this.清除已绘制图形ToolStripMenuItem.Text = "清除已绘制图形"; this.清除已绘制图形ToolStripMenuItem.Click += new System.EventHandler(this.清除已绘制图形ToolStripMenuItem_Click); // // panel1 // this.panel1.Controls.Add(this.splitContainer1); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(0, 60); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(1042, 585); this.panel1.TabIndex = 2; // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(0, 0); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.groupBoxEagleEye); this.splitContainer1.Panel1.Controls.Add(this.axTOCControl1); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.statusStrip1); this.splitContainer1.Panel2.Controls.Add(this.axLicenseControl1); this.splitContainer1.Panel2.Controls.Add(this.axMapControl1); this.splitContainer1.Size = new System.Drawing.Size(1042, 585); this.splitContainer1.SplitterDistance = 247; this.splitContainer1.TabIndex = 0; // // groupBoxEagleEye // this.groupBoxEagleEye.Controls.Add(this.axMapControl2); this.groupBoxEagleEye.Dock = System.Windows.Forms.DockStyle.Bottom; this.groupBoxEagleEye.Location = new System.Drawing.Point(0, 261); this.groupBoxEagleEye.Name = "groupBoxEagleEye"; this.groupBoxEagleEye.Size = new System.Drawing.Size(247, 324); this.groupBoxEagleEye.TabIndex = 2; this.groupBoxEagleEye.TabStop = false; this.groupBoxEagleEye.Text = "鹰眼导航"; // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.lblCoordinate, this.lblResult, this.toolStripStatusLabel1}); this.statusStrip1.Location = new System.Drawing.Point(0, 556); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Padding = new System.Windows.Forms.Padding(2, 0, 14, 0); this.statusStrip1.Size = new System.Drawing.Size(791, 29); this.statusStrip1.TabIndex = 0; this.statusStrip1.Text = "statusStrip1"; // // lblCoordinate // this.lblCoordinate.Name = "lblCoordinate"; this.lblCoordinate.Size = new System.Drawing.Size(644, 24); this.lblCoordinate.Spring = true; this.lblCoordinate.Text = "lblCoordinate"; this.lblCoordinate.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // lblResult // this.lblResult.Name = "lblResult"; this.lblResult.Size = new System.Drawing.Size(85, 24); this.lblResult.Text = "lblResult"; // // axLicenseControl1 // this.axLicenseControl1.Enabled = true; this.axLicenseControl1.Location = new System.Drawing.Point(757, 528); this.axLicenseControl1.Name = "axLicenseControl1"; this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState"))); this.axLicenseControl1.Size = new System.Drawing.Size(32, 32); this.axLicenseControl1.TabIndex = 1; // // txtRotateAngle // this.txtRotateAngle.Name = "txtRotateAngle"; this.txtRotateAngle.Size = new System.Drawing.Size(100, 23); // // contextMenuStripTOC // this.contextMenuStripTOC.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.openAttributeTableToolStripMenuItem}); this.contextMenuStripTOC.Name = "contextMenuStripTOC"; this.contextMenuStripTOC.Size = new System.Drawing.Size(171, 32); // // openAttributeTableToolStripMenuItem // this.openAttributeTableToolStripMenuItem.Name = "openAttributeTableToolStripMenuItem"; this.openAttributeTableToolStripMenuItem.Size = new System.Drawing.Size(170, 28); this.openAttributeTableToolStripMenuItem.Text = "打开属性表"; this.openAttributeTableToolStripMenuItem.Click += new System.EventHandler(this.openAttributeTableToolStripMenuItem_Click); // // axMapControl2 // this.axMapControl2.Dock = System.Windows.Forms.DockStyle.Fill; this.axMapControl2.Location = new System.Drawing.Point(3, 24); this.axMapControl2.Name = "axMapControl2"; this.axMapControl2.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axMapControl2.OcxState"))); this.axMapControl2.Size = new System.Drawing.Size(241, 297); this.axMapControl2.TabIndex = 0; // // axTOCControl1 // this.axTOCControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.axTOCControl1.Location = new System.Drawing.Point(0, 0); this.axTOCControl1.Name = "axTOCControl1"; this.axTOCControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axTOCControl1.OcxState"))); this.axTOCControl1.Size = new System.Drawing.Size(247, 585); this.axTOCControl1.TabIndex = 0; this.axTOCControl1.OnMouseDown += new ESRI.ArcGIS.Controls.ITOCControlEvents_Ax_OnMouseDownEventHandler(this.axTOCControl1_OnMouseDown); // // axMapControl1 // this.axMapControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.axMapControl1.Location = new System.Drawing.Point(0, 0); this.axMapControl1.Name = "axMapControl1"; this.axMapControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axMapControl1.OcxState"))); this.axMapControl1.Size = new System.Drawing.Size(791, 585); this.axMapControl1.TabIndex = 0; this.axMapControl1.OnMouseDown += new ESRI.ArcGIS.Controls.IMapControlEvents2_Ax_OnMouseDownEventHandler(this.axMapControl1_OnMouseDown); this.axMapControl1.OnMouseMove += new ESRI.ArcGIS.Controls.IMapControlEvents2_Ax_OnMouseMoveEventHandler(this.axMapControl1_OnMouseMove); this.axMapControl1.OnDoubleClick += new ESRI.ArcGIS.Controls.IMapControlEvents2_Ax_OnDoubleClickEventHandler(this.axMapControl1_OnDoubleClick); // // axToolbarControl1 // this.axToolbarControl1.Dock = System.Windows.Forms.DockStyle.Top; this.axToolbarControl1.Location = new System.Drawing.Point(0, 32); this.axToolbarControl1.Name = "axToolbarControl1"; this.axToolbarControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axToolbarControl1.OcxState"))); this.axToolbarControl1.Size = new System.Drawing.Size(1042, 28); this.axToolbarControl1.TabIndex = 1; // // 折线周长量测ToolStripMenuItem // this.折线周长量测ToolStripMenuItem.Name = "折线周长量测ToolStripMenuItem"; this.折线周长量测ToolStripMenuItem.Size = new System.Drawing.Size(206, 28); this.折线周长量测ToolStripMenuItem.Text = "折线周长量测"; this.折线周长量测ToolStripMenuItem.Click += new System.EventHandler(this.折线周长量测ToolStripMenuItem_Click); // // toolStripStatusLabel1 // this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; this.toolStripStatusLabel1.Size = new System.Drawing.Size(46, 24); this.toolStripStatusLabel1.Text = "就绪"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1042, 645); this.Controls.Add(this.panel1); this.Controls.Add(this.axToolbarControl1); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "供水管网地理信息系统"; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.Load += new System.EventHandler(this.Form1_Load); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.panel1.ResumeLayout(false); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); this.splitContainer1.Panel2.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); this.groupBoxEagleEye.ResumeLayout(false); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit(); this.contextMenuStripTOC.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.axMapControl2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem1; private ESRI.ArcGIS.Controls.AxToolbarControl axToolbarControl1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.SplitContainer splitContainer1; private ESRI.ArcGIS.Controls.AxMapControl axMapControl1; private System.Windows.Forms.StatusStrip statusStrip1; private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1; private ESRI.ArcGIS.Controls.AxTOCControl axTOCControl1; private System.Windows.Forms.ToolStripStatusLabel lblCoordinate; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem2; private System.Windows.Forms.ToolStripTextBox txtRotateAngle; private System.Windows.Forms.GroupBox groupBoxEagleEye; private ESRI.ArcGIS.Controls.AxMapControl axMapControl2; private System.Windows.Forms.ContextMenuStrip contextMenuStripTOC; private System.Windows.Forms.ToolStripMenuItem openAttributeTableToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem3; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem4; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem5; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem6; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem7; private System.Windows.Forms.ToolStripMenuItem 清除选择ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem 空间量测ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem 面积量测ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem 周长量测ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem 点坐标量测ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem 清除已绘制图形ToolStripMenuItem; private System.Windows.Forms.ToolStripStatusLabel lblResult; private System.Windows.Forms.ToolStripMenuItem 折线周长量测ToolStripMenuItem; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; } } 此代码我想实现鹰眼导航(即在此代码中,mapcontrol控件(axMapControl1)中显示的是主地图,而左下角的mapcontrol控件(axMapControl2)进行鹰眼导航,axMapControl1中的视野范围在axMapControl2中用深蓝色边框进行框起来。无论是主视图大小缩放还是通过鼠标移动视角,在axMapControl2都要跟着框起来,他固定不动但是蓝色边框跟着移动)注意我的vs版本为2010,给出完整的修改代码,要细致的修改操作教程
07-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值