2012년 3월 31일 토요일

물량정리 LISP 만들기

배이직도면 상의 마크와 사이즈 정보 그리고 라인을이용한 물건의 길이를
txt파일로 저장한다.


베이직도면의 정보얻기
베이직도면에 명기돼는 멤버리스트를 txt파일로저장
ex)...("mark" "h400x300x8x13")

이렉션 드로잉상의 선택한 마크와 저장된 마크를 매치해서 사이즈를 파일로 쓴다.




;basic도면의 부재 싸이즈를 txt파일로
(defun c:atest (/ startPoint endPoint startPointArea
endPointArea stp2 edp2
v_len1 v_len2 v_len3 fd
file_m count pointTest areaList
xDistance xAngle sn en
)

  (setq var_osmode (getvar "osmode"))
  (setvar "osmode" 32)
  (setq pointTest nil)
  (setq areaList nil)
  (setq count 1)


  (prompt "\n한줄의 영역을 지정해주세요.")
  (setq startPoint (getpoint "\n시작점"))
  (setq endPoint (getcorner startPoint "\n두번째점"))
  (setq xDistance (distance startPoint endPoint))
  (setq xAngle (angle startPoint endPoint))



  (prompt "\n문자열이 포함된 영역을 지정해주세요")

  (while (= pointTest nil)
(setq startPointArea (getpoint "\n시작점"))

(if (/= startPointArea nil)
 (progn
(setq endPointArea (getcorner startPointArea "\n두번째점"))
(setq areaList
  (append
areaList
(append (list startPointArea) (list endPointArea))
  )
)
(setq count (+ count 1))
 )
 (setq pointTest 1)
)
  )

  (setq file_m (file_name2))

  (if (= file_m nil)
(setq file_m file_i)
(setq file_i file_m)
  )



  (setq v_len1 (abs (- (cadr startPoint) (cadr endPoint))))



  (setq sn 0)
  (setq en 1)

  (while (/= count 0)

(setq startPointArea (nth sn areaList))
(setq endPointArea (nth en areaList))
(setq v_len2 (abs (- (cadr startPointArea) (cadr endPointArea))))
(setq v_len3 (atoi (rtos (/ v_len2 v_len1) 2 0)))



(setvar "osmode" 0)

(repeat v_len3
 (setq a1 (ssget "c" startPoint endPoint '((0 . "text"))))
 (if (/= a1 nil)
(progn
 (setq fd (open file_m "a"))
 (princ (basic_mark a1) fd)
 (princ "\n" fd)
 (close fd)
)
 )
;;;선택영역에 텍스트가없으면 파일에 쓰지않음
 (setq stp2 (polar startPoint (+ pi (/ pi 2)) v_len1))
 (setq edp2 (polar endPoint (+ pi (/ pi 2)) v_len1))
 (setq startPoint
stp2
endPoint edp2
 )
)
(setq sn (+ sn 2))
(setq en (+ en 2))
(setq count (- count 1))
(if (/= count 1)
 (progn
(setq startPoint (nth sn areaList))
(setq endPoint (polar startPoint xAngle xDistance))
 )
 (setq count 0)
)
  )
  (setvar "osmode" var_osmode)
  (princ)

)


(defun basic_mark
  (a1 / num n a2 a3 a4 a5 b1 b2 b3 len_b1 len_b2 b6 b11 b22)
;;;a1~a5선택세트
;;;n 반복용
;;;len~ 길이를 이용한 정렬
;;;b~ 출력


; (setq a1(ssget "w" startPoint endPoint))
  (setq num (sslength a1))
  (setq n 0)

  (repeat 2

(setq a2 (ssname a1 n))
(setq a3 (entget a2))
(setq a4 (assoc 1 a3))
(setq a5 (cdr a4))

(if (= n 0)
 (setq b1 a5)
 (setq b2 a5)
)

(setq n (+ n 1))
  )

  (setq len_b1 (strlen b1))
  (setq len_b2 (strlen b2))
;(setq b6 nil)

  (if (> len_b1 len_b2)
(progn
 (setq b6 b1)
 (setq b1 b2)
 (setq b2 b6)
)
  )
  (setq b11 (strcat "\"" b1 "\""))
  (setq b22 (strcat "\"" b2 "\""))
  (setq b3 (list b11 b22))
)
;;;선택세트에서 문자열을 정리해서 리턴

(defun file_name2 (/ path_m name_m file_m) ;

;(setq path_m "c:/hello/")
  (setq path_m "C:/hmgTXT/")
  (setq name_m (getstring "\n파일이름을 입력하세요."))
  (if (= name_m "")
(setq file_m nil)
(setq file_m (strcat path_m name_m ".txt"))
  )

  file_m

)



;;;파일에서 읽어온문자를 도면의 글자와 대치해서 삽입

(defun c:etest (/ selectObjectSet
entname ent   num
n entTextvalueList
insertPoint textAngle   blockinsertPoint
entTextvalue markSize   file_m thelist
dcl_id selectFilevalue listboxValue listBoxtest
)

  (vl-load-com)
  (setq val_dimscale (getvar "dimscale"))
  (setq val_cmdho (getvar "cmdecho"))
  (setq val_attdia (getvar "attdia"))
  (setvar "attdia" 0)
  (setq val3 (/ val_dimscale 2))

  (setvar "cmdecho" 0)

  (setq thelist (vl-directory-files "C:/hmgTXT/" "*.txt" 1))

  (setq dcl_id (load_dialog "basicMarkFile.dcl"))


  (if (not (new_dialog "basicMarkFile" dcl_id))
(exit)
  )

  (start_list "selectFile")
  (mapcar 'add_list thelist)
  (end_list)

  (action_tile "cancel" "(setq listBoxtest 1) (done_dialog)")
  (action_tile
"accept"
"(setq listboxValue (atoi(get_tile \"selectFile\")))(done_dialog)"
  )


  (start_dialog)
  (unload_dialog dcl_id)
  (if (/= listBoxtest nil)
(exit)
(progn

  (setq selectFilevalue (nth listboxValue thelist))


  (setq file_m (file_name3 selectFilevalue))
  (if (= file_m nil)
(setq file_m file_i)
(setq file_i file_m)
  )

  (prompt "\n선택")

  (setq selectObjectSet
(ssget) ;"<or" '((0 . "text")) '((0 . "line")) "or>"
  )
  (setq num (sslength selectObjectSet))
  (setq n 0)

  (repeat num

(setq entname (ssname selectObjectSet n))
(setq ent (entget entname))
(cond
 ((= (cdr (assoc 0 ent)) "TEXT")

  (setq entTextvalueList (assoc 1 ent))
  (setq entTextvalue (cdr entTextvalueList))

  (setq insertPoint (cdr (assoc 10 ent)))
  (setq textAngle (cdr (assoc 50 ent)))
  (setq blockinsertPoint
 (polar insertPoint
(+ textAngle (+ pi (/ pi 2)))
(+ val_dimscale (/ val_dimscale 3))
 )
  )
  (setq textAngle_t (* 180 (/ textAngle pi)))

  (setq markSize (car (edwg_mark entTextvalue file_m)))
 )

 ((= (cdr (assoc 0 ent)) "LINE")

  (setq lineStartPoint (cdr (assoc 10 ent)))
  (setq llineEndPoint (cdr (assoc 11 ent)))
  (setq lineLength
 (rtos (distance lineStartPoint llineEndPoint) 2 0)
  )
 )
)
(setq n (+ n 1))
  )
  (command "-insert" "C:/hmgTXT/basicMark/hmg_mark" blockinsertPoint
  val_dimscale textAngle_t lineLength
  markSize entTextvalue
 )
  )
)
  (setvar "attdia" val_attdia)
  (princ)
)



(defun edwg_mark (entTextvalue file_m / fd r1 r2 r3 r4 i) ;

  (setq i 0)
  (setq fd (open file_m "r"))

  (if (= fd nil)
(alert "\n존재하지 않는파일입니다.")
  )

  (while (= i 0)

(setq r1 (read-line fd))

(if (= r1 nil)
 (progn
(setq r4 (list "nothing"))
(setq i 1)
 )
 (progn
(setq r2 (read r1))
(setq r3 (car r2))
 )
)


(if (= r3 entTextvalue)
 (progn
(setq r4 (cdr r2))
(setq i 1)
 )
)

  )
  (close fd)
  r4
)


(defun file_name3 (selectFilevalue / path_m name_m file_m) ;

;(setq path_m "c:/hello/")
  (setq path_m "C:/hmgTXT/")
  (setq name_m selectFilevalue)
  (if (= name_m "")
(setq file_m nil)
(setq file_m (strcat path_m name_m))
  )

  file_m

)



;dcl은 별도로
(defun c:mtest( / a b c)
  (setq a "C:/hmgTXT/basicMark/hmg_mark.txt")
  (setq b "C:/hmgTXT/basicMark/markSizeList.txt")
  (setq c (ssget '((2 . "hmg_mark"))))
  (command "-attext" "o" c "" "s" a b)
  (princ)
  )


basicMarkFile : dialog{
label = "Basic Mark File List";
: list_box {
label = "File List";
key = "selectFile";
}


ok_cancel;
}



2012년 3월 28일 수요일

Set and Return System Variables(시스템변수)


// Get the current value from a system variable
int nMaxSort = System.Convert.ToInt32(Application.GetSystemVariable("MAXSORT"));

// Set system variable to new value
Application.SetSystemVariable("MAXSORT", 100);

2012년 3월 27일 화요일

Calculate Points and Values(포인트와 값 계산)


Get angle from X-axis
(angle)


using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;

[CommandMethod("AngleFromXAxis")]
public static void AngleFromXAxis()
{
  Point2d pt1 = new Point2d(2, 5);
  Point2d pt2 = new Point2d(5, 2);

  Application.ShowAlertDialog("Angle from XAxis: " +
                              pt1.GetVectorTo(pt2).Angle.ToString());
}


Calculate Polar Point
(polar)

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;

static Point2d PolarPoints(Point2d pPt, double dAng, double dDist)
{
  return new Point2d(pPt.X + dDist * Math.Cos(dAng),
                     pPt.Y + dDist * Math.Sin(dAng));
}

static Point3d PolarPoints(Point3d pPt, double dAng, double dDist)
{
  return new Point3d(pPt.X + dDist * Math.Cos(dAng),
                     pPt.Y + dDist * Math.Sin(dAng),
                     pPt.Z);
}

[CommandMethod("PolarPoints")]
public static void PolarPoints()
{
  Point2d pt1 = PolarPoints(new Point2d(5, 2), 0.785398, 12);

  Application.ShowAlertDialog("\nPolarPoint: " +
                              "\nX = " + pt1.X +
                              "\nY = " + pt1.Y);

  Point3d pt2 = PolarPoints(new Point3d(5, 2, 0), 0.785398, 12);

  Application.ShowAlertDialog("\nPolarPoint: " +
                              "\nX = " + pt2.X +
                              "\nY = " + pt2.Y +
                              "\nZ = " + pt2.Z);
}

Find the distance between two points with the GetDistance method
(distance)


using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("GetDistanceBetweenTwoPoints")]
public static void GetDistanceBetweenTwoPoints()
{
  Document acDoc = Application.DocumentManager.MdiActiveDocument;

  PromptDoubleResult pDblRes;
  pDblRes = acDoc.Editor.GetDistance("\nPick two points: ");

  Application.ShowAlertDialog("\nDistance between points: " +
                              pDblRes.Value.ToString());
}




출처
http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%20.NET%20Developer's%20Guide/index.html

GetString Method



using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("GetStringFromUser")]
public static void GetStringFromUser()
{
  Document acDoc = Application.DocumentManager.MdiActiveDocument;

  PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter your name: ");
  pStrOpts.AllowSpaces = true;
  PromptResult pStrRes = acDoc.Editor.GetString(pStrOpts);

  Application.ShowAlertDialog("The name entered was: " +
                              pStrRes.StringResult);
}

2012년 3월 26일 월요일

GetPoint Method




using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("GetPointsFromUser")]
public static void GetPointsFromUser()
{
  // Get the current database and start the Transaction Manager
  Document acDoc = Application.DocumentManager.MdiActiveDocument;
  Database acCurDb = acDoc.Database;

  PromptPointResult pPtRes;
  PromptPointOptions pPtOpts = new PromptPointOptions("");

  //public PromptPointOptions(string message)


  // Prompt for the start point
  pPtOpts.Message = "\nEnter the start point of the line: "; //생성자에 넘겨주어도 됌
  pPtRes = acDoc.Editor.GetPoint(pPtOpts);
  Point3d ptStart = pPtRes.Value;


  // Exit if the user presses ESC or cancels the command
  if (pPtRes.Status == PromptStatus.Cancel) return;

  // Prompt for the end point
  pPtOpts.Message = "\nEnter the end point of the line: ";
  pPtOpts.UseBasePoint = true;  //public bool UseBasePoint { set; get; }
  pPtOpts.BasePoint = ptStart;
  pPtRes = acDoc.Editor.GetPoint(pPtOpts);
  Point3d ptEnd = pPtRes.Value;

  if (pPtRes.Status == PromptStatus.Cancel) return;

  // Start a transaction
  using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
  {
      BlockTable acBlkTbl;
      BlockTableRecord acBlkTblRec;

      // Open Model space for write
      acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                   OpenMode.ForRead) as BlockTable;

      acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
                                      OpenMode.ForWrite) as BlockTableRecord;

      // Define the new line
      Line acLine = new Line(ptStart, ptEnd);
      acLine.SetDatabaseDefaults();

      // Add the line to the drawing
      acBlkTblRec.AppendEntity(acLine);
      acTrans.AddNewlyCreatedDBObject(acLine, true);

      // Zoom to the extents or limits of the drawing
      acDoc.SendStringToExecute("._zoom _all ", true, false, false);

      // Commit the changes and dispose of the transaction
      acTrans.Commit();
  }
}

//두점을 입력받아 선을그리고 줌한다.


출처
http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%20.NET%20Developer's%20Guide/index.html

2012년 3월 23일 금요일

hmgScript

개요

내컴퓨터에 있는 dwg파일을 선택해서 일괄 작업을 해주는 CAD script파일을 작성한다.
미리작성한 스크립 파일을 이용해서 선택한 dwg파일의 경로와 목록이 포함됀 스크립 파일을
작성한다.
사전정의됀 스크립선택버튼 = 콤보박스
미등록 사용자정의 스크립파일 선택버튼 = 콤보박스 or 버튼
작성버튼으로 지정됀 폴더에 hmg_script.scr파일을 작성한다.

캐드의 scr명령을 이용해서 작성됀 스크립파일을 실행한다.

createScriptFile class
string dwgfile_location//선택한 도면의 경로
string[] dwgList//선택한도면의 목록
string[] read_scrfile_contants//스크립파일내용 읽기

void create_scr()//작성


2012년 3월 19일 월요일

작업할 폴더를 선택해서 작업할 파일목록을 불러오기


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 System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.ShowDialog();
            string aa = folderBrowserDialog1.SelectedPath;

            if (Directory.Exists(aa))
            {
                foreach (string f in Directory.GetFiles(aa))
                {
                    listBox1.Items.Add(f);
                }
            }
           
        }
    }
}

listbox에 지정경로의 파일목록을 불러온다.

지정경로의 파일목록 가져오기

using System.IO;if (Directory.Exists(path)){    foreach (string f in Directory.GetFiles(path))    {        // 리스트 박스나 기타 다른 반복된 작업 수행    }}


위에서 파일 경로는 path에 지정하면 됨
foreach 문에서 반복적으로 파일경로+파일명+파일확장자를 가져와서 처리할 수 있음


출처
http://redcarrot.tistory.com/37

FolderBrowserDialog


이 클래스는 폴더를 찾아보고, 만들고 경우에 따라 선택하도록 사용자에게 요구하는 방법을 제공합니다.이 클래스는 파일이 아닌 폴더를 선택할 수 있게 하려는 경우에만 사용합니다.폴더 찾아보기는 트리 컨트롤을 통해 수행됩니다.파일 시스템의 폴더만 선택할 수 있으며 가상 폴더는 선택할 수 없습니다.

일반적으로 새 FolderBrowserDialog를 만든 후에 RootFolder를 찾아보기를 시작할 위치로 설정합니다.또는 SelectedPath를 처음에 선택될 RootFolder의 하위 폴더에 대한 절대 경로로 설정할 수도 있습니다.뿐만 아니라 Description 속성을 설정하여 사용자에게 추가 지침을 제공할 수도 있습니다.마지막으로 ShowDialog 메서드를 호출하여 사용자에게 대화 상자를 표시합니다.대화 상자가 닫히고 ShowDialog의 대화 상자 결과가 DialogResult.OK이면 SelectedPath는 선택된 폴더의 경로를 포함하는 문자열이 됩니다.

ShowNewFolderButton 속성을 사용하여 사용자가 새 폴더 단추로 새 폴더를 만들 수 있는지 여부를 제어할 수 있습니다.

FolderBrowserDialog는 모달 대화 상자이므로 이 대화 상자가 표시되면 폴더를 선택할 때까지 나머지 응용 프로그램을 사용할 수 없습니다.모달 대화 상자가 표시되면 대화 상자의 개체를 제외한 아무런 입력 작업(키보드 또는 마우스 클릭)도 수행할 수 없습니다.프로그램은 일반적으로 호출 프로그램에 대한 입력이 발생하기 전에 일부 사용자 동작에 대한 응답으로 대화 상자를 숨기거나 닫아야 합니다.



2012년 3월 16일 금요일

TEKLA SPLIT시 주의

객체의 포인드가 레퍼런스 포인트가 되어버린다.
그러니 자를 때 주의 요망.
실재 재작에는 상관이야 없는  사항이지만 주의 해서 나쁠것 없다.

2012년 3월 12일 월요일

기본문법

생성자


class와 이름이 같고 public으로 선언 매소드와같이 매개변수를 가질수있지만 (안가질수도 있지만)
반환형이 없다.
new  를 이용해서 인스턴스 생성시 매개변수를 넘겨주어서 필드를 초기화 할수있다.


class 변수명 = new 생성자();//생성자 메소드
class 변수명;//class 복합데이타 타입의 변수가 생성이돼는데 참조형식이다.
new 생성자()//힙에 인스턴스(실체)를 만들고 변수명이 이를 가리키게 한다.

프로퍼티

private string name;
public string name
{
     get{ return name;}
     set{ name = value;}
}

오버로딩(Overloading)

메소드를 만들떼 같은 기능이지만 매개변수가 다를 경우 오버로딩 기능이 없을경우
새로운 메소드를 만들어야한다.

2012년 3월 11일 일요일

Content type


Type  Description
template attributes.

ASSEMBLY
 Use to create lists of assemblies and single parts. Includes all assemblies containing the selected parts and bolts.

BOLT
 Use to create screw and bolt lists. Includes all bolts connected to selected parts.

CAST_UNIT
 Use to create lists of cast units.

CHAMFER
 Use to create lists of the length of the chamfers.

COMMENT
 Use to create empty rows or rows that only have textual data or lines anywhere on a template.

CONNECTION
 Use to create lists of connections.

DRAWING
 Use to create drawing lists without revision history information. Use for reports and included drawings.

HOLE
 Use to create lists of holes.

MESH
 Use to create lists of meshes.

NUT
 Use to create lists of nuts. Contains all nuts for bolts associated with the selected parts.

PART
 Use to create lists of parts.

REBAR
 Use to create lists of reinforcing bars.

REFERENCE_MODEL
 Use to list the reference models.

REFERENCE_OBJECT
 Use to list the reference model objects in a reference model.

Only reference model objects that have user-defined attributes are displayed in reports.

REVISION
 Use to create lists of revision marks.

SIMILAR_ASSEMBLY
 Use to create lists of similar parts.

To use this content type, you need to have an empty (hidden in output ASSEMBLY, PART or CAST_UNIT row in row hierarchy above the row with SIMILAR_* content type:




You cannot have any rows below SIMILAR_* row content type in the row hierarchy.

SIMILAR_CAST_UNIT

SIMILAR_PART

SINGLE_REBAR
 Use to create lists of individual bars in reinforcing bar groups.

For example, use it to the get the lengths of the individual bars in tapered reinforcing bar groups.

SINGLE_STRAND
 Use to create lists of individual prestressed strands.

STRAND
 Use to create lists of prestressed strands.

STUD
 Use to create lists of studs.

SURFACING
 Use to create lists of surfacings.

SUMMARY
 Use to summarize the contents of the row(s) that are above SUMMARY in the hierarchy.




For example, use PART - SUMMARY hierarchy to summarize the contents of the PART rows.

WASHER
 Use to create lists of washers. Contains all washers for all bolts associated with the selected parts.

WELD
 Use to create lists of welds.




2012년 3월 9일 금요일

Add a named view and set it current

//뷰를 세로 만들고 현제로 설정


using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;

[CommandMethod("CreateNamedView")]
public static void CreateNamedView()
{
  // Get the current database
  Document acDoc = Application.DocumentManager.MdiActiveDocument;
  Database acCurDb = acDoc.Database;

  // Start a transaction
  using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
  {
      // Open the View table for read
      ViewTable acViewTbl;
      acViewTbl = acTrans.GetObject(acCurDb.ViewTableId,
                                    OpenMode.ForRead) as ViewTable;

      // Check to see if the named view 'View1' exists
      //"VIEW1"이라는 뷰가있는지 먼저 확인을 한다.
      if (acViewTbl.Has("View1") == false)
      {
          // Open the View table for write
          acViewTbl.UpgradeOpen();

          // Create a new View table record and name the view 'View1'
          ViewTableRecord acViewTblRec = new ViewTableRecord();
          acViewTblRec.Name = "View1";

          // Add the new View table record to the View table and the transaction
          acViewTbl.Add(acViewTblRec);
          acTrans.AddNewlyCreatedDBObject(acViewTblRec, true);

          // Set 'View1' current
          acDoc.Editor.SetCurrentView(acViewTblRec);

          // Commit the changes
          acTrans.Commit();
      }

      // Dispose of the transaction
  }
}

Zoom

Zoom to an area defined by two points
[CommandMethod("ZoomWindow")]
static public void ZoomWindow()
{
  // Zoom to a window boundary defined by 1.3,7.8 and 13.7,-2.6
  Point3d pMin = new Point3d(1.3, 7.8, 0);
  Point3d pMax = new Point3d(13.7, -2.6, 0);

  Zoom(pMin, pMax, new Point3d(), 1);
}
두 인자에 대한 좌표 (1.3,7.8,0)와이 (13.7, -2.6,0)을 표시하는 영역을 정의하기 위해 전달됩니다.

Zoom in on the active drawing using a specified scale
[CommandMethod("ZoomScale")]

static public void ZoomScale()
{
  // Get the current document
  Document acDoc = Application.DocumentManager.MdiActiveDocument;

  // Get the current view
  using (ViewTableRecord acView = acDoc.Editor.GetCurrentView())
  {
      // Get the center of the current view
      Point3d pCenter = new Point3d(acView.CenterPoint.X,
                                    acView.CenterPoint.Y, 0);

      // Set the scale factor to use
      double dScale = 0.5;

      // Scale the view using the center of the current view
      Zoom(new Point3d(), new Point3d(), pCenter, 1 / dScale);
  }
}

ZOOM SCALE 그런건가보다.

Zoom in on the active drawing to a specified center

[CommandMethod("ZoomCenter")]
static public void ZoomCenter()
{
  // Center the view at 5,5,0
  Zoom(new Point3d(), new Point3d(), new Point3d(5, 5, 0), 1);
}


이건 ZOOM OBJECT정도

Display Drawing Extents and Limits

[CommandMethod("ZoomExtents")]
static public void ZoomExtents()
{
  // Zoom to the extents of the current space
  Zoom(new Point3d(), new Point3d(), new Point3d(), 1.01075);
}

[CommandMethod("ZoomLimits")]
static public void ZoomLimits()
{
  Document acDoc = Application.DocumentManager.MdiActiveDocument;
  Database acCurDb = acDoc.Database;

  // Zoom to the limits of Model space
  Zoom(new Point3d(acCurDb.Limmin.X, acCurDb.Limmin.Y, 0),
       new Point3d(acCurDb.Limmax.X, acCurDb.Limmax.Y, 0),
       new Point3d(), 1);
}
ZOOM EXTEND인듯.



출처
http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%20.NET%20Developer%27s%20Guide/index.html

Manipulate the Current View(현제 뷰 조작)

Some of the common properties that you will use to manipulate the current view are:
//현제뷰의 조작을 위해 사용하는 속성

CenterPoint - Center point of a view in DCS coordinates.
//dcs죄표의 중심???

Height - Height of a view in DCS coordinates. Increase the height to zoom out;
decrease the height to zoom in.

Target - Target of a view in WCS coordinates.

ViewDirection - Vector from the target to the camera of a view in WCS coordinates.

ViewTwist - Twist angle in radians of a view.

Width - Width of a view in DCS coordinates. Increase the width to zoom out; decrease the width to zoom in.

The parameters of the Zoom procedure are:
//줌 프로시져의 매개변수(프로시져면 함수?)


Minimum point - 3D point used to define the lower-left corner of the area to display.
//왼쪽아레

Maximum point - 3D point used to define the upper-right corner of the area to display.
//오른쪽위

Center point - 3D point used to define the center of a view.

Scale factor - Real number used to specify the scale to increase or decrease the size of a view.



using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Geometry;

static void Zoom(Point3d pMin, Point3d pMax, Point3d pCenter, double dFactor)
{
  // Get the current document and database
  Document acDoc = Application.DocumentManager.MdiActiveDocument;
  Database acCurDb = acDoc.Database;

  int nCurVport = System.Convert.ToInt32(Application.GetSystemVariable("CVPORT"));

  // Get the extents of the current space no points
  // or only a center point is provided
  // Check to see if Model space is current
  if (acCurDb.TileMode == true)
  {
      if (pMin.Equals(new Point3d()) == true &&
          pMax.Equals(new Point3d()) == true)
      {
          pMin = acCurDb.Extmin;
          pMax = acCurDb.Extmax;
      }
  }
  else
  {
      // Check to see if Paper space is current
      if (nCurVport == 1)
      {
          // Get the extents of Paper space
          if (pMin.Equals(new Point3d()) == true &&
              pMax.Equals(new Point3d()) == true)
          {
              pMin = acCurDb.Pextmin;
              pMax = acCurDb.Pextmax;
          }
      }
      else
      {
          // Get the extents of Model space
          if (pMin.Equals(new Point3d()) == true &&
              pMax.Equals(new Point3d()) == true)
          {
              pMin = acCurDb.Extmin;
              pMax = acCurDb.Extmax;
          }
      }
  }

  // Start a transaction
  using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
  {
      // Get the current view
      using (ViewTableRecord acView = acDoc.Editor.GetCurrentView())
      {
          Extents3d eExtents;

          // Translate WCS coordinates to DCS
          Matrix3d matWCS2DCS;
          matWCS2DCS = Matrix3d.PlaneToWorld(acView.ViewDirection);
          matWCS2DCS = Matrix3d.Displacement(acView.Target - Point3d.Origin) * matWCS2DCS;
          matWCS2DCS = Matrix3d.Rotation(-acView.ViewTwist,
                                         acView.ViewDirection,
                                         acView.Target) * matWCS2DCS;

          // If a center point is specified, define the min and max
          // point of the extents
          // for Center and Scale modes
          if (pCenter.DistanceTo(Point3d.Origin) != 0)
          {
              pMin = new Point3d(pCenter.X - (acView.Width / 2),
                                 pCenter.Y - (acView.Height / 2), 0);

              pMax = new Point3d((acView.Width / 2) + pCenter.X,
                                 (acView.Height / 2) + pCenter.Y, 0);
          }

          // Create an extents object using a line
          using (Line acLine = new Line(pMin, pMax))
          {
              eExtents = new Extents3d(acLine.Bounds.Value.MinPoint,
                                       acLine.Bounds.Value.MaxPoint);
          }

          // Calculate the ratio between the width and height of the current view
          double dViewRatio;
          dViewRatio = (acView.Width / acView.Height);

          // Tranform the extents of the view
          matWCS2DCS = matWCS2DCS.Inverse();
          eExtents.TransformBy(matWCS2DCS);

          double dWidth;
          double dHeight;
          Point2d pNewCentPt;

          // Check to see if a center point was provided (Center and Scale modes)
          if (pCenter.DistanceTo(Point3d.Origin) != 0)
          {
              dWidth = acView.Width;
              dHeight = acView.Height;

              if (dFactor == 0)
              {
                  pCenter = pCenter.TransformBy(matWCS2DCS);
              }

              pNewCentPt = new Point2d(pCenter.X, pCenter.Y);
          }
          else // Working in Window, Extents and Limits mode
          {
              // Calculate the new width and height of the current view
              dWidth = eExtents.MaxPoint.X - eExtents.MinPoint.X;
              dHeight = eExtents.MaxPoint.Y - eExtents.MinPoint.Y;

              // Get the center of the view
              pNewCentPt = new Point2d(((eExtents.MaxPoint.X + eExtents.MinPoint.X) * 0.5),
                                       ((eExtents.MaxPoint.Y + eExtents.MinPoint.Y) * 0.5));
          }

          // Check to see if the new width fits in current window
          if (dWidth > (dHeight * dViewRatio)) dHeight = dWidth / dViewRatio;

          // Resize and scale the view
          if (dFactor != 0)
          {
              acView.Height = dHeight * dFactor;
              acView.Width = dWidth * dFactor;
          }

          // Set the center of the view
          acView.CenterPoint = pNewCentPt;

          // Set the current view
          acDoc.Editor.SetCurrentView(acView);
      }

      // Commit the changes
      acTrans.Commit();
  }
}

출처
http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%20.NET%20Developer%27s%20Guide/index.html


Position and Size the Document Window

Size the active Document window



using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Windows;

[CommandMethod("SizeDocumentWindow")]
public static void SizeDocumentWindow()
{
  // Size the Document window
  Document acDoc = Application.DocumentManager.MdiActiveDocument;
  acDoc.Window.WindowState = Window.State.Normal;

  // Set the position of the Document window
  Point ptDoc  = new Point(0, 0);
  acDoc.Window.Location = ptDoc;

  // Set the size of the Document window
  Size szDoc = new Size(400, 400);
  acDoc.Window.Size = szDoc;
}


Minimize and maximize the active Document window
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Windows;

[CommandMethod("MinMaxDocumentWindow")]
public static void MinMaxDocumentWindow()
{
  Document acDoc = Application.DocumentManager.MdiActiveDocument;

  // Minimize the Document window
  acDoc.Window.WindowState = Window.State.Minimized;
  System.Windows.Forms.MessageBox.Show("Minimized" , "MinMax");

  // Maximize the Document window
  acDoc.Window.WindowState = Window.State.Maximized;
  System.Windows.Forms.MessageBox.Show("Maximized" , "MinMax");
}

Find the current state of the active Document window
//현제상태
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Windows;

[CommandMethod("CurrentDocWindowState")]
public static void CurrentDocWindowState()
{
  Document acDoc = Application.DocumentManager.MdiActiveDocument;

  System.Windows.Forms.MessageBox.Show("The document window is " +
  acDoc.Window.WindowState.ToString(), "Window State");
}

출처
http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%20.NET%20Developer%27s%20Guide/index.html


Control the Application Window


Position and size the Application window
(PresentationCore.dll을 참조추가 해야한다.)
using System.Drawing;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;

[CommandMethod("PositionApplicationWindow")]
public static void PositionApplicationWindow()
{
  // Set the position of the Application window
  //응용 프로그램 윈도우의 위치를 설정
  Point ptApp = new Point(0, 0);
  Application.MainWindow.Location = ptApp;

  // Set the size of the Application window
  //응용 프로그램 창의 크기를 설정
  Size szApp = new Size(400, 400);
  Application.MainWindow.Size = szApp;
}

Minimize and maximize the Application window
using System.Drawing;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Windows;

[CommandMethod("MinMaxApplicationWindow")]
public static void MinMaxApplicationWindow()
{
  // Minimize the Application window
  Application.MainWindow.WindowState = Window.State.Minimized;
  System.Windows.Forms.MessageBox.Show("Minimized", "MinMax",
              System.Windows.Forms.MessageBoxButtons.OK,
              System.Windows.Forms.MessageBoxIcon.None,
              System.Windows.Forms.MessageBoxDefaultButton.Button1,
              System.Windows.Forms.MessageBoxOptions.ServiceNotification);

  // Maximize the Application window
  Application.MainWindow.WindowState = Window.State.Maximized;
  System.Windows.Forms.MessageBox.Show("Maximized", "MinMax");
}


Find the current state of the Application window
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Windows;

[CommandMethod("CurrentWindowState")]
public static void CurrentWindowState()
{
  System.Windows.Forms.MessageBox.Show("The application window is " +
                                       Application.MainWindow.WindowState.ToString(),
                                       "Window State");
}

Make the Application window invisible and visible
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Windows;

[CommandMethod("HideWindowState")]
public static void HideWindowState()
{
  // Hide the Application window
  Application.MainWindow.Visible = false;
  System.Windows.Forms.MessageBox.Show("Invisible", "Show/Hide");

  // Show the Application window
  Application.MainWindow.Visible = true;
  System.Windows.Forms.MessageBox.Show("Visible", "Show/Hide");
}

출처
http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%20.NET%20Developer%27s%20Guide/index.html



2012년 3월 8일 목요일

Out-of-Process versus In-Process


using System;
using System.Runtime.InteropServices;

using Autodesk.AutoCAD.Interop;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;

[CommandMethod("ConnectToAcad")]
public static void ConnectToAcad()
{

  AcadApplication acAppComObj = null;
  const string strProgId = "AutoCAD.Application.18";
  //const는 상수를 만드는 것 같음...

  // Get a running instance of AutoCAD
  try
  {
      acAppComObj = (AcadApplication)Marshal.GetActiveObject(strProgId);
  }
  catch // An error occurs if no instance is running
  {
      try
      {
          // Create a new instance of AutoCAD
          // 실행중인 AutoCAD의 인스턴스 (instance)에 접근
        acAppComObj = (AcadApplication)Activator.CreateInstance(Type.GetTypeFromProgID(strProgId), true);
      }
      catch
      {
          // If an instance of AutoCAD is not created then message and exit
          System.Windows.Forms.MessageBox.Show("Instance of 'AutoCAD.Application'" +
                                               " could not be created.");

          return;
      }
  }

  // Display the application and return the name and version
  acAppComObj.Visible = true;
  System.Windows.Forms.MessageBox.Show("Now running " + acAppComObj.Name +
                                       " version " + acAppComObj.Version);

  // Get the active document
  AcadDocument acDocComObj;
  acDocComObj = acAppComObj.ActiveDocument;

  // Optionally, load your assembly and start your command or if your assembly
  // is demandloaded, simply start the command of your in-process assembly.
  acDocComObj.SendCommand("(command " + (char)34 + "NETLOAD" + (char)34 + " " +
                          (char)34 + "c:/myapps/mycommands.dll" + (char)34 + ") ");

  acDocComObj.SendCommand("MyCommand ");
}

모르겠다...
출처
http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%20.NET%20Developer%27s%20Guide/index.html

Erase a Member of a Collection Object


using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;

[CommandMethod("RemoveMyLayer")]
public static void RemoveMyLayer()
{
  // Get the current document and database, and start a transaction
  Document acDoc = Application.DocumentManager.MdiActiveDocument;
  Database acCurDb = acDoc.Database;

  using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
  {
      // Returns the layer table for the current database
      LayerTable acLyrTbl;
      acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
                                   OpenMode.ForRead) as LayerTable;

      // Check to see if MyLayer exists in the Layer table
      if (acLyrTbl.Has("MyLayer") == true)
      {
          LayerTableRecord acLyrTblRec;
          acLyrTblRec = acTrans.GetObject(acLyrTbl["MyLayer"],
                                          OpenMode.ForWrite) as LayerTableRecord;

          try
          {
              acLyrTblRec.Erase();
              acDoc.Editor.WriteMessage("\n'MyLayer' was erased");

              // Commit the changes
              acTrans.Commit();
          }
          catch
          {
              acDoc.Editor.WriteMessage("\n'MyLayer' could not be erased");
          }
      }
      else
      {
          acDoc.Editor.WriteMessage("\n'MyLayer' does not exist");
      }

      // Dispose of the transaction
  }
}

출처
http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%20.NET%20Developer%27s%20Guide/index.html

Iterate through a Collection Object

acObjId = acLyrTbl["MyLayer"];




using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;

[CommandMethod("IterateLayers")]
public static void IterateLayers()
{
  // Get the current document and database, and start a transaction
  Document acDoc = Application.DocumentManager.MdiActiveDocument;
  Database acCurDb = acDoc.Database;

  using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
  {
      // This example returns the layer table for the current database
      //현재 데이터베이스 레이어 테이블을 반환
      LayerTable acLyrTbl;
      acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
                                   OpenMode.ForRead) as LayerTable;

      // Step through the Layer table and print each layer name
      //레이어 테이블을 통해 단계와 각 레이어의 이름을 인쇄
      foreach (ObjectId acObjId in acLyrTbl)
      {
          LayerTableRecord acLyrTblRec;
          acLyrTblRec = acTrans.GetObject(acObjId,
                                          OpenMode.ForRead) as LayerTableRecord;

          acDoc.Editor.WriteMessage("\n" + acLyrTblRec.Name);
      }

      // Dispose of the transaction
  }
}

LayerTable 개체에 MyLayer라는 레이어 테이블 레코드 찾기
다음 예제는 MyLayer라는 레이어가 존재하거나하지 않을 경우 결정 LayerTable 개체를확인하고, 적절한 메시지를 표시합니다



using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;


[CommandMethod("FindMyLayer")]
public static void FindMyLayer()
{
  // Get the current document and database, and start a transaction
  Document acDoc = Application.DocumentManager.MdiActiveDocument;
  Database acCurDb = acDoc.Database;


  using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
  {
      // Returns the layer table for the current database
      LayerTable acLyrTbl;
      acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
                                   OpenMode.ForRead) as LayerTable;


      // Check to see if MyLayer exists in the Layer table
      //MyLayer는 레이어 테이블에 존재하는지 확인
      if (acLyrTbl.Has("MyLayer") != true)
      {
          acDoc.Editor.WriteMessage("\n'MyLayer' does not exist");
      }
      else
      {
          acDoc.Editor.WriteMessage("\n'MyLayer' exists");
      }


      // Dispose of the transaction
  }
}

출처
http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%20.NET%20Developer%27s%20Guide/index.html

Add a New Member to a Collection Object

컬렉션에 새 구성원을 추가하려면 Add 메서드를 사용합니다. 예를 들어, 다음 코드는 새 레이어를 만들고 레이어 테이블에 추가합니다 :



using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;

[CommandMethod("AddMyLayer")]
public static void AddMyLayer()
{
  // Get the current document and database, and start a transaction
  //현재 문서 및 데이터베이스 찾아, 트랜잭션을 시작합니다
  Document acDoc = Application.DocumentManager.MdiActiveDocument;
  Database acCurDb = acDoc.Database;

  using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
  {
      // Returns the layer table for the current database
      //현재 데이터베이스 레이어 테이블을 반환
      LayerTable acLyrTbl;
      acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
                                   OpenMode.ForRead) as LayerTable;

      // Check to see if MyLayer exists in the Layer table
      //MyLayer는 레이어 테이블에 존재하는지 확인
      if (acLyrTbl.Has("MyLayer") != true)
      {
          // Open the Layer Table for write
          //쓰기위한 레이어 테이블을 엽니다
          acLyrTbl.UpgradeOpen();

          // Create a new layer table record and name the layer "MyLayer"
          //새 레이어 테이블 레코드를 만들고 레이어 "MyLayer"을 지정
          LayerTableRecord acLyrTblRec = new LayerTableRecord();
          acLyrTblRec.Name = "MyLayer";

          // Add the new layer table record to the layer table and the transaction
          //레이어 테이블과 트랜잭션에 새 레이어 테이블 레코드 추가
          acLyrTbl.Add(acLyrTblRec);
          acTrans.AddNewlyCreatedDBObject(acLyrTblRec, true);

          // Commit the changes
          //변경 내용을 적용
          acTrans.Commit();
      }

      // Dispose of the transaction
  }
}


출처
http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%20.NET%20Developer%27s%20Guide/index.html

Access a Collection


// Get the current document and start the Transaction Manager
//현재 문서를 가져와서 트랜잭션 관리자를 시작합니다
Database acCurDb = Application.DocumentManager.MdiActiveDocument.Database;
using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
{
    // This example returns the layer table for the current database
    LayerTable acLyrTbl;
    acLyrTbl = acTrans.GetObject(acCurDb.LayerTableId,
                                 OpenMode.ForRead) as LayerTable;

     // Dispose of the transaction
}


출처
http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%20.NET%20Developer%27s%20Guide/index.html

Collection Objects


Block Table Record
특정 블록 정의 내의 모든 개체를 포함합니다.

Block Table
도면의 모든 블록을 포함합니다.

Named Objects Dictionary
드로잉의 모든 사전을 포함합니다.(오브잭트 사전?)

Dimension Style Table
도면의 모든 치수 스타일을 포함합니다.

Document Collection
현재 세션에서 열려있는 모든 도면을 포함합니다.

File Dependency Collection
파일 종속성 목록의 모든 항목을 포함합니다.

Group Dictionary
드로잉의 모든 그룹을 포함합니다.

Hyperlink Collection
주어진 개체의 모든 하이퍼 링크를 포함합니다.

Layer Table
드로잉에있는 모든 레이어를 포함합니다.

Layout Dictionary
드로잉의 모든 레이아웃을 포함합니다.

Linetype Table
드로잉의 모든 linetypes을 포함합니다.

MenuBar Collection
현재의 AutoCAD에 표시되는 모든 메뉴를 포함합니다.

MenuGroup Collection
현재의 AutoCAD에 로드된 모든 사용자 지정 그룹을 포함합니다.사용자 지정 그룹은 사용자 인터페이스를 정의하는 다른 요소들 사이에서 메뉴, 도구 모음 및 리본 탭을 포함할 수 로드된 CUIx 파일을 나타냅니다.

Plot Configuration Dictionary
도면의 명명된 플롯 설정을 포함합니다.

Registered Application Table
드로잉의 모든 등록된 응용 프로그램을 포함합니다.

Text Style Table
드로잉에있는 모든 텍스트 스타일을 포함합니다.

UCS Table
드로잉의 모든 사용자 좌표 시스템 (UCS의)가 포함되어 있습니다.

View Table
드로잉의 모든 전경을 포함합니다.

Viewport Table
드로잉의 모든 viewports을 포함합니다.

2012년 3월 7일 수요일

Reference Objects in the Object Hierarchy 객체 계층 구조의 참조 객체



string strFName, strBlkName;
Autodesk.AutoCAD.DatabaseServices.ObjectId objId;

strFName = "c:/clients/Proj 123/grid.dwg";
strBlkName = System.IO.Path.GetFileNameWithoutExtension(strFName);

objId = Application.DocumentManager.MdiActiveDocument.Database.AttachXref(strFName, strBlkName);


//현제도면의 데이터베이스에 그림파일을 첨부
//데이터베이스 객체에서 AttachXref()메소드가 호출됀다.


Autodesk.AutoCAD.DatabaseServices.Database acCurDb;
acCurDb = Application.DocumentManager.MdiActiveDocument.Database;

//Autodesk.AutoCAD.DatabaseServices.Database의 변수 (acCurDb)를 정의하고
//현재 문서의 데이터베이스를 넘겨줌.


string strFName, strBlkName;
Autodesk.AutoCAD.DatabaseServices.ObjectId objId;

strFName = "c:/clients/Proj 123/grid.dwg";
strBlkName = System.IO.Path.GetFileNameWithoutExtension(strFName);

objId = acCurDb.AttachXref(strFName, strBlkName);

//acCurDb를 이용해서 그림첨부

//현제활성됀 문서(도면)에 참조문서(도면)을 첨부한다.





using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;

[CommandMethod("ListEntities")]
public static void ListEntities()
{
  // Get the current document and database, and start a transaction
  Document acDoc = Application.DocumentManager.MdiActiveDocument;
  //문서객체타입의 변수를 만들고 현제활성 문서를 저장.
  Database acCurDb = acDoc.Database;
  //데이터베이스객체타입의 변수에 현제문서의 데이터베이스를 저장.

  using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
  {  
      //트렌잭션 시작 데이터베이스에 접근해서 변경이나 값을 읽어 올수있다.
      // Open the Block table record for read
      BlockTable acBlkTbl;
      acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,
                                   OpenMode.ForRead) as BlockTable;

      // Open the Block table record Model space for read
      BlockTableRecord acBlkTblRec;
      acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],
                                      OpenMode.ForRead) as BlockTableRecord;

      int nCnt = 0;
      acDoc.Editor.WriteMessage("\nModel space objects: ");

      // Step through each object in Model space and
      // display the type of object found
      foreach (ObjectId acObjId in acBlkTblRec)
      {
          acDoc.Editor.WriteMessage("\n" + acObjId.ObjectClass.DxfName);

          nCnt = nCnt + 1;
      }

      // If no objects are found then display a message
      if (nCnt == 0)
      {
          acDoc.Editor.WriteMessage("\n No objects found");
      }

      // Dispose of the transaction
  }
}


출처
http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%20.NET%20Developer%27s%20Guide/index.html

Access the Object Hierarchy 개체계층구조에 엑세스

Application.DocumentManager.MdiActiveDocument.Database.Clayer;
//Application개체의 DocumentManager속성의 MdiActiveDocument 프로퍼티를 이용해서

 현재 문서에 액세스할 수 있다.
MdiActiveDocument 속성에 의해 반환된 문서 개체에서, 데이터베이스 속성으로 데이터베이스에 액세스할 수 있다.




출처
http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%20.NET%20Developer%27s%20Guide/index.html

2012년 3월 6일 화요일

다중 필터 Specify Multiple Criteria in a Selection Filter


using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;

[CommandMethod("FilterBlueCircleOnLayer0")]
public static void FilterBlueCircleOnLayer0()
{
  // Get the current document editor
  Editor acDocEd = Application.DocumentManager.MdiActiveDocument.Editor;

  // Create a TypedValue array to define the filter criteria
  TypedValue[] acTypValAr = new TypedValue[3];
  acTypValAr.SetValue(new TypedValue((int)DxfCode.Color, 5), 0);
  acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "CIRCLE"), 1);
  acTypValAr.SetValue(new TypedValue((int)DxfCode.LayerName, "0"), 2);
  //필터링 내용을 TypedValue[]의 인스턴스에 지정한다.
 
  // Assign the filter criteria to a SelectionFilter object
  SelectionFilter acSelFtr = new SelectionFilter(acTypValAr);

  //SelectionFilte인스턴스를 만들고 성정한 필터값 배열을 이용해서 초기화 한다.

  // Request for objects to be selected in the drawing area
  PromptSelectionResult acSSPrompt;
  acSSPrompt = acDocEd.GetSelection(acSelFtr);
  //선택필터값을 프롬프트 인스턴스에 넘겨프롬프트에 출력.???

  // If the prompt status is OK, objects were selected
  if (acSSPrompt.Status == PromptStatus.OK)
  {
      SelectionSet acSSet = acSSPrompt.Value;

      Application.ShowAlertDialog("Number of objects selected: " +
                                  acSSet.Count.ToString());
  }
  else
  {
      Application.ShowAlertDialog("Number of objects selected: 0");
  }
}

원 이면서 레이어가 "0"인 객체를 필터링

출처
http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%20.NET%20Developer's%20Guide/index.html

선택 Use Selection Filters to Define Selection Set Rules


using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;

[CommandMethod("FilterSelectionSet")]
public static void FilterSelectionSet()
{
  // Get the current document editor
  Editor acDocEd = Application.DocumentManager.MdiActiveDocument.Editor;

  // Create a TypedValue array to define the filter criteria
  TypedValue[] acTypValAr = new TypedValue[1];
  acTypValAr.SetValue(new TypedValue((int)DxfCode.Start, "CIRCLE"), 0);

  // Assign the filter criteria to a SelectionFilter object
  SelectionFilter acSelFtr = new SelectionFilter(acTypValAr);

  // Request for objects to be selected in the drawing area
  PromptSelectionResult acSSPrompt;
  acSSPrompt = acDocEd.GetSelection(acSelFtr);

  // If the prompt status is OK, objects were selected
  if (acSSPrompt.Status == PromptStatus.OK)
  {
      SelectionSet acSSet = acSSPrompt.Value;

      Application.ShowAlertDialog("Number of objects selected: " +
                                  acSSet.Count.ToString());
  }
  else
  {
      Application.ShowAlertDialog("Number of objects selected: 0");
  }
}


출처 http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%20.NET%20Developer's%20Guide/index.html

2012년 3월 5일 월요일

transaction

데이터베이스 데이터의 무결성을 위한 장치같은 것인가보다.
데이터의 수정과정에서 오류가 없으면 갱신이 돼며
오류나 중도에 수정을 취소할 경우 데이터는 갱신돼지 않고 이전의 상태로 도아간다.

2012년 3월 2일 금요일

static메소드

public static void 메소드( )
static 으로 메소드를 선언할경우 인스턴스를 통하지않아도 호출이 가능하다.

static으로 서언 돼지않았다면 인스턴스를 통해야 메소드를 호출할수있다.