Option Strict Off Option Explicit On Imports System Imports System.Threading Imports System.Collections.Generic Imports Microsoft.VisualBasic Imports System.Windows.Forms Module ZunoFrameDimension Private minX As Double = Double.PositiveInfinity Private minY As Double = Double.PositiveInfinity Private maxX As Double = Double.NegativeInfinity Private maxY As Double = Double.NegativeInfinity Private geometryCount As Integer = 0 Private inspectedCount As Integer = 0 Private groupCount As Integer = 0 Private arcCount As Integer = 0 Private unknown As New Dictionary(Of Integer, Integer)() Private Const Gap As Double = 10.0R Private Const MaxInspected As Integer = 20000 Private Const PI As Double = 3.1415926535897931R Public Sub Main() Dim root As Object = Nothing Dim app As Object = Nothing Dim doc As Object = Nothing Dim selecting As Boolean = False Dim stage As String = "connect" Dim addedCount As Integer = 0 Dim completedFrames As Integer = 0 Dim scaleText As String = "未取得" Try root = Interaction.CreateObject("zwDrawCAD.Object") app = root.Application doc = app.GetDoc() If doc Is Nothing Then ShowWarning("図脳RAPIDの図面が開かれていません。" & vbCrLf & vbCrLf & _ "図面を開いてから、もう一度「10」ボタンを押してください。") Return End If ' Keep the automation active across separate selections. ' ESC or starting another CAD command makes GetSelectStatus return 0, ' and ends the session without an ordinary completion dialog. Do ResetBounds() addedCount = 0 stage = "SelectStart" If Not CBool(doc.SelectStart()) Then Throw New Exception("SelectStart failed.") selecting = True Dim selected As Integer = -1 stage = "GetSelectStatus" Do Thread.Sleep(150) selected = CInt(doc.GetSelectStatus()) If selected >= 0 Then Exit Do Loop If selected = 0 Then ' ESC or an interrupting CAD command: ordinary exit. Exit Do End If ' CAD may count selected members inside groups (e.g. 218 lines) ' even when the selected top-level list only contains three groups. ' Traverse the actual top-level list until its documented tail ID. ' Recursively count its leaf elements BEFORE any drawing. stage = "選択図形とグループの照合" Dim topCount As Integer = 0 Dim position As Integer = CInt(doc.GetSelectHeadPosition()) Dim tailPosition As Integer = CInt(doc.GetSelectTailPosition()) Dim visitedTop As New HashSet(Of Integer)() If selected > MaxInspected Then Throw New Exception("選択数が上限を超えました。") If position <= 0 OrElse tailPosition <= 0 Then Throw New Exception("選択リストの先頭または末尾を取得できません。") Dim reachedTail As Boolean = False For i As Integer = 1 To MaxInspected If position <= 0 OrElse Not visitedTop.Add(position) Then Throw New Exception("選択リストに無効なIDまたは重複があります。") topCount += 1 ReadElement(doc, position, 0) If position = tailPosition Then reachedTail = True Exit For End If position = CInt(doc.GetSelectNextPosition(position)) Next If Not reachedTail Then Throw New Exception("選択リストの末尾まで確認できませんでした。") ' Some CAD settings return the top-level count; others report ' the total number of selected primitives inside groups. ' Accept either only when traversal reached the documented tail. If selected <> topCount AndAlso selected <> geometryCount Then Throw New Exception("図形数が一致しません。選択=" & selected.ToString() & _ " / グループ等=" & topCount.ToString() & " / 内部図形=" & geometryCount.ToString()) End If Dim counts As String = "Selected top-level elements: " & selected.ToString() & vbCrLf & _ "Inspected incl. group members: " & inspectedCount.ToString() & vbCrLf & _ "Groups: " & groupCount.ToString() & vbCrLf & _ "Geometry elements read: " & geometryCount.ToString() & " (arcs: " & arcCount.ToString() & ")" & vbCrLf If unknown.Count > 0 Then Dim unsupported As String = "" For Each pair As KeyValuePair(Of Integer, Integer) In unknown unsupported &= "kind " & pair.Key.ToString() & " : " & pair.Value.ToString() & vbCrLf Next ShowWarning("選択した図形の中に、外形を読み取れないものがあります。" & vbCrLf & vbCrLf & _ "部品の外形だけを囲み直してください。" & vbCrLf & _ "10mm枠と寸法線は作図していません。" & vbCrLf & vbCrLf & _ "参考:対応していない図形番号" & vbCrLf & unsupported) Return End If If geometryCount = 0 Then Throw New Exception("No geometric elements could be read.") Dim width As Double = maxX - minX Dim height As Double = maxY - minY If width <= 0 OrElse height <= 0 Then Throw New Exception("Invalid width or height.") ' Release CAD selection before any drawing operation. stage = "SelectEnd" If Not CBool(doc.SelectEnd()) Then Throw New Exception("SelectEnd failed. No lines were drawn.") selecting = False ' Read the scale already verified with the preview test. stage = "GetScale" Dim denom As Integer = 0, numer As Integer = 0 If Not CBool(doc.GetScale(denom, numer)) Then Throw New Exception("GetScale failed.") If denom <= 0 OrElse numer <= 0 Then Throw New Exception("Invalid drawing scale.") scaleText = numer.ToString() & "/" & denom.ToString() Dim offset As Double = 10.0R * CDbl(denom) / CDbl(numer) If Double.IsNaN(offset) OrElse Double.IsInfinity(offset) OrElse offset <= 0 OrElse offset > 1000000 Then _ Throw New Exception("Invalid dimension offset.") ' Dimension the OUTER 10 mm frame itself. ' Example: product 200x100 -> frame 220x120. ' Dimension offset is measured FROM THE FRAME, not from the product. Dim frameLeft As Double = minX - Gap Dim frameRight As Double = maxX + Gap Dim frameBottom As Double = minY - Gap Dim frameTop As Double = maxY + Gap Dim xMid As Double = (minX + maxX) / 2.0R Dim yMid As Double = (minY + maxY) / 2.0R ' Use temporary OLE modal settings so the user's ordinary CAD ' layer and pen settings are not permanently changed. ' Modal layer 3 is green in the example drawing. ' Style 3 = short one-dot chain (S1C_PATTERN). ' Force layer 3 (green in this drawing) for *this automation only*. ' SetModalLayer does NOT change the regular CAD current layer. stage = "SetModalLayer" If Not CBool(doc.SetModalLayer(CInt(3))) Then _ Throw New Exception("Could not switch temporary OLE drawing layer to 3.") Dim modalLayer As Integer = 0 stage = "GetModalLayer" If Not CBool(doc.GetModalLayer(modalLayer)) OrElse modalLayer <> 3 Then _ Throw New Exception("Temporary OLE layer was not set to 3 (value: " & modalLayer.ToString() & ").") stage = "SetModalPenStyle" If Not CBool(doc.SetModalPenStyle(CShort(3))) Then _ Throw New Exception("Could not set short one-dot chain line type.") stage = "SetModalPenColor" ' The manual says SetModalPenColor may return False even when it ' succeeds, so do not rely on its return value. doc.SetModalPenColor(CShort(0), CShort(150), CShort(50)) stage = "SetModalPenWidth" doc.SetModalPenWidth(CShort(1)) ' V20: Construct the complete rectangle as ONE CAD geometry element. ' Undo will be tested in the target CAD: a single AddPolyLine2 call ' may yield a single history step, unlike four AddLine calls. ' First vertex is repeated at the end to close the boundary. stage = "AddPolyLine2 rectangle" Dim pts() As Double = New Double() { _ frameLeft, frameBottom, _ frameRight, frameBottom, _ frameRight, frameTop, _ frameLeft, frameTop, _ frameLeft, frameBottom _ } Dim polyPos As Integer = CInt(doc.AddPolyLine2(pts, CShort(5), CShort(0))) If polyPos <= 0 Then Throw New Exception("AddPolyLine2 returned an invalid element index.") addedCount += 1 stage = "Verify frame polyline" If CInt(doc.GetKind(polyPos)) <> 64 Then _ Throw New Exception("Created frame was not a polyline (kind 64).") Dim actualLayer As Integer = -1 If Not CBool(doc.GetLayer(polyPos, actualLayer)) OrElse actualLayer <> 3 Then _ Throw New Exception("The created polyline is not on layer 3.") ' No PackS call: the single polyline is already selected/moved as one ' object, and adding a separate group operation could add an undo step. ' Create dimensions after the frame so Ctrl+Z removes: ' right dimension -> bottom dimension -> 10mm frame. stage = "Set dimension layer" If Not CBool(doc.SetModalLayer(CInt(3))) Then Throw New Exception("SetModalLayer(3) failed.") stage = "Set dimension line style" If Not CBool(doc.SetModalPenStyle(CShort(0))) Then Throw New Exception("SetModalPenStyle(0) failed.") doc.SetModalPenColor(CShort(0), CShort(150), CShort(50)) doc.SetModalPenWidth(CShort(1)) stage = "AddDimensionSingle horizontal (outer frame)" Dim hDim As Integer = CInt(doc.AddDimensionSingle( _ frameLeft, frameBottom, frameRight, frameBottom, xMid, frameBottom - offset, 0.0R)) If hDim <= 0 Then Throw New Exception("Horizontal dimension API returned 0.") addedCount += 1 stage = "AddDimensionSingle vertical (outer frame)" Dim vDim As Integer = CInt(doc.AddDimensionSingle( _ frameRight, frameBottom, frameRight, frameTop, frameRight + offset, yMid, 90.0R)) If vDim <= 0 Then Throw New Exception("Vertical dimension API returned 0.") addedCount += 1 stage = "Clear selection" If Not CBool(doc.SelectAll(False)) Then _ Throw New Exception("Could not clear the selection.") stage = "Redraw" doc.Redraw() completedFrames += 1 ' No success pop-up: immediately let the user window-select ' another cutting figure, or press ESC to finish. Loop Catch ex As Exception Dim detail As String = ExplainError(stage) Dim partialMessage As String = If(addedCount > 0, _ "今回の処理では図形が一部だけ残っている可能性があります。", _ "今回の処理では枠・寸法線が追加されていない可能性が高いです。") Dim errorMessage As String = "10mm枠と寸法線を最後まで作図できませんでした。" & vbCrLf & vbCrLf & _ "【確認すること】" & vbCrLf & detail & vbCrLf & vbCrLf & _ "【作図状況】" & vbCrLf & _ "今回作成した要素:" & addedCount.ToString() & " / 3" & vbCrLf & _ "読み取った縮尺:" & scaleText & vbCrLf & _ "それまでに正常終了した部品:" & completedFrames.ToString() & "個" & vbCrLf & vbCrLf & _ "【対処方法】" & vbCrLf & partialMessage & vbCrLf & _ "図面を確認し、不要な線は元に戻してください。" & vbCrLf & _ "不安な場合は保存せずに図面を閉じてください。" & vbCrLf & vbCrLf & _ "解決しない場合は、この画面をスクリーンショットで送ってください。" & vbCrLf & _ "(処理名:" & stage & ")" & vbCrLf & _ "(詳細:" & ex.Message & ")" ShowWarning(errorMessage) Finally If selecting AndAlso Not doc Is Nothing Then Try doc.SelectEnd() Catch End Try End If doc = Nothing app = Nothing root = Nothing End Try End Sub Private Function ExplainError(ByVal stage As String) As String Select Case stage Case "connect" Return "図脳RAPIDとの接続に失敗しました。CADが起動しているか確認してください。" Case "SelectStart", "GetSelectStatus", "Read selected groups", "選択図形とグループの照合", "SelectEnd" Return "図形を正しく選択できませんでした。部品の外形だけを囲んでEnterを押してください。" Case "GetScale" Return "図面の縮尺を読み取れませんでした。図面の縮尺設定を確認してください。" Case "Set dimension layer", "Set dimension line style" Return "寸法線を作るためのレイヤ・線種設定に失敗しました。レイヤ3が使えるか確認してください。" Case "AddDimensionSingle horizontal (outer frame)" Return "横方向の寸法線を作図できませんでした。図形の幅やレイヤ設定を確認してください。" Case "AddDimensionSingle vertical (outer frame)" Return "縦方向の寸法線を作図できませんでした。図形の高さやレイヤ設定を確認してください。" Case "SetModalLayer", "GetModalLayer", "SetModalPenStyle", "SetModalPenColor", "SetModalPenWidth" Return "10mm枠の色・線種・レイヤ設定に失敗しました。レイヤ3を確認してください。" Case "AddPolyLine2 rectangle", "Verify frame polyline" Return "10mm枠を作図・確認できませんでした。部品の外形やレイヤ設定を確認してください。" Case "Clear selection", "Redraw" Return "作図後の画面更新が正常に終了しませんでした。図面の表示を確認してください。" Case Else Return "図形の大きさや選択範囲を確認して、もう一度お試しください。" End Select End Function Private Sub ShowWarning(ByVal message As String) ' On errors only, create a temporary topmost owner window so the warning ' is not hidden behind the CAD window. The owner is disposed immediately. Try Using owner As New Form() owner.Text = "10mm枠・寸法線の確認" owner.TopMost = True owner.ShowInTaskbar = False owner.StartPosition = FormStartPosition.CenterScreen owner.FormBorderStyle = FormBorderStyle.FixedToolWindow owner.Size = New System.Drawing.Size(1, 1) owner.Opacity = 0.0R owner.Show() owner.Activate() System.Windows.Forms.MessageBox.Show(owner, message, "10mm枠・寸法線:確認", _ MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) End Using Catch ' Fallback if Windows Forms cannot create a temporary owner. Interaction.MsgBox(message, CType(CInt(MsgBoxStyle.Exclamation) Or _ CInt(MsgBoxStyle.SystemModal) Or &H10000, MsgBoxStyle), "10mm枠・寸法線:確認") End Try End Sub Private Function FormatDimensionValue(ByVal value As Double) As String ' Japanese CAD drawings: avoid decimals on integer dimensions, and ' do not depend on Windows locale for the decimal separator. Return value.ToString("0.###", System.Globalization.CultureInfo.InvariantCulture) End Function Private Sub ResetBounds() minX = Double.PositiveInfinity minY = Double.PositiveInfinity maxX = Double.NegativeInfinity maxY = Double.NegativeInfinity geometryCount = 0 inspectedCount = 0 groupCount = 0 arcCount = 0 unknown.Clear() End Sub Private Function F(ByVal v As Double) As String Return v.ToString("0.###", Globalization.CultureInfo.InvariantCulture) End Function Private Sub AddPoint(ByVal x As Double, ByVal y As Double) If Double.IsNaN(x) OrElse Double.IsNaN(y) OrElse Double.IsInfinity(x) OrElse Double.IsInfinity(y) Then Throw New Exception("Invalid coordinates found.") End If minX = Math.Min(minX, x) maxX = Math.Max(maxX, x) minY = Math.Min(minY, y) maxY = Math.Max(maxY, y) End Sub Private Sub AddArcBounds(ByVal cx As Double, ByVal cy As Double, ByVal r As Double, _ ByVal startDeg As Double, ByVal endDeg As Double) If r <= 0 Then Throw New Exception("Invalid arc radius.") Dim delta As Double = endDeg - startDeg If Math.Abs(delta) >= 360.0R - 0.00000001R OrElse Math.Abs(delta) < 0.00000001R Then AddPoint(cx - r, cy - r) AddPoint(cx + r, cy + r) Return End If Dim sweep As Double = PositiveMod(delta, 360.0R) AddPoint(cx + r * Math.Cos(startDeg * PI / 180.0R), cy + r * Math.Sin(startDeg * PI / 180.0R)) AddPoint(cx + r * Math.Cos(endDeg * PI / 180.0R), cy + r * Math.Sin(endDeg * PI / 180.0R)) For Each card As Double In New Double() {0.0R, 90.0R, 180.0R, 270.0R} If PositiveMod(card - startDeg, 360.0R) <= sweep + 0.00000001R Then AddPoint(cx + r * Math.Cos(card * PI / 180.0R), cy + r * Math.Sin(card * PI / 180.0R)) End If Next End Sub Private Function PositiveMod(ByVal value As Double, ByVal modulus As Double) As Double Return ((value Mod modulus) + modulus) Mod modulus End Function Private Sub UnknownKind(ByVal kind As Integer) If Not unknown.ContainsKey(kind) Then unknown(kind) = 0 unknown(kind) += 1 End Sub Private Sub ReadElement(ByVal doc As Object, ByVal pos As Integer, ByVal depth As Integer) If depth > 12 OrElse pos <= 0 Then Throw New Exception("Invalid group nesting / element index.") inspectedCount += 1 If inspectedCount > MaxInspected Then Throw New Exception("Safety limit exceeded: too many elements.") Dim kind As Integer = CInt(doc.GetKind(pos)) Select Case kind Case 1 ' line Dim x1 As Double = 0.0R, y1 As Double = 0.0R Dim x2 As Double = 0.0R, y2 As Double = 0.0R If Not CBool(doc.GetLine(pos, x1, y1, x2, y2)) Then Throw New Exception("GetLine failed (element " & pos & ").") AddPoint(x1, y1) AddPoint(x2, y2) geometryCount += 1 Case 2 ' circle Dim cx As Double = 0.0R, cy As Double = 0.0R, r As Double = 0.0R If Not CBool(doc.GetCircle(pos, cx, cy, r)) Then Throw New Exception("GetCircle failed (element " & pos & ").") If r <= 0 Then Throw New Exception("Invalid circle radius.") AddPoint(cx - r, cy - r) AddPoint(cx + r, cy + r) geometryCount += 1 Case 4 ' circular arc Dim cx As Double = 0.0R, cy As Double = 0.0R, r As Double = 0.0R Dim st As Double = 0.0R, et As Double = 0.0R If Not CBool(doc.GetArc(pos, cx, cy, r, st, et)) Then Throw New Exception("GetArc failed (element " & pos & ").") AddArcBounds(cx, cy, r, st, et) geometryCount += 1 arcCount += 1 Case 8 ' full ellipse Dim cx As Double = 0.0R, cy As Double = 0.0R Dim xr As Double = 0.0R, yr As Double = 0.0R, angle As Double = 0.0R If Not CBool(doc.GetEllipse(pos, cx, cy, xr, yr, angle)) Then Throw New Exception("GetEllipse failed (element " & pos & ").") If xr <= 0 OrElse yr <= 0 Then Throw New Exception("Invalid ellipse radii.") Dim theta As Double = angle * PI / 180.0R Dim dx As Double = Math.Sqrt(Math.Pow(xr * Math.Cos(theta), 2) + Math.Pow(yr * Math.Sin(theta), 2)) Dim dy As Double = Math.Sqrt(Math.Pow(xr * Math.Sin(theta), 2) + Math.Pow(yr * Math.Cos(theta), 2)) AddPoint(cx - dx, cy - dy) AddPoint(cx + dx, cy + dy) geometryCount += 1 Case 64 ' polyline, not spline Dim polyType As Short = 0 If Not CBool(doc.GetPolyLineType(pos, polyType)) Then Throw New Exception("GetPolyLineType failed.") If polyType <> 0 Then UnknownKind(64) Return End If Dim n As Integer = 0 If Not CBool(doc.GetPolyLineCount(pos, n)) Then Throw New Exception("GetPolyLineCount failed.") If n <= 0 OrElse n > MaxInspected Then Throw New Exception("Invalid polyline point count.") For i As Integer = 0 To n - 1 Dim x As Double = 0.0R, y As Double = 0.0R If Not CBool(doc.GetPolyLinePoint(pos, i, x, y)) Then Throw New Exception("GetPolyLinePoint failed.") AddPoint(x, y) Next geometryCount += 1 Case 1024 ' group groupCount += 1 Dim child As Integer = CInt(doc.GetGroupHeadPosition(pos)) Dim lastChild As Integer = CInt(doc.GetGroupTailPosition(pos)) If child <= 0 Then Throw New Exception("Empty or invalid group (element " & pos & ").") Dim visited As New HashSet(Of Integer)() Dim reachedLast As Boolean = False For i As Integer = 1 To MaxInspected If child <= 0 OrElse visited.Contains(child) Then Throw New Exception("Group traversal failed (element " & pos & ").") visited.Add(child) ReadElement(doc, child, depth + 1) If child = lastChild Then reachedLast = True Exit For End If Dim nextChild As Integer = CInt(doc.GetGroupNextPosition(pos, child)) If nextChild <= 0 OrElse nextChild = child Then Throw New Exception("Group list ended unexpectedly.") child = nextChild Next If Not reachedLast Then Throw New Exception("Group did not reach its last element.") Case Else ' Do not silently exclude unsupported shapes, text or dimensions. UnknownKind(kind) End Select End Sub End Module