기본 콘텐츠로 건너뛰기

2013의 게시물 표시

.NET Automation

.NET Automation /// SP3D CommonMiddle Registry /// 13.12.12 static FormMain() { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler); } /// /// SP3D CommonMiddle Registry /// /// 13.12.12 public static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) { //This handler is called only when the common language runtime tries to bind to the assembly and fails. //Retrieve the list of referenced assemblies in an array of AssemblyName. //Loop through the array of referenced assemblies. foreach (AssemblyName strAssmbName in Assembly.GetExecutingAssembly().GetReferencedAssemblies()) { //Look for the assembly names that have raised the "AssemblyResolve" event. if (((strAssmbName.Name.EndsWith("CommonMiddle")) /*&& (strAssmbName.FullName.Substring(0, strAssmbName.FullName.IndexOf(",")) == args.Name.Substring(0, args.Name.IndexOf(",")))) ? 1 : 0) != 0*/)) { //We only hav

프린터 속성 설정하기

아래는 프린터 속성을 설정하는 함수입니다. 원문보기 #include <WinSpool.h> /** @brief set printer property @author humkyung @date 2013.11.06 @param pPrinterName @param dmType @param dmValue **/ STDMETHODIMP CISODwgLib4IDCS::SetPrinterProperty(BSTR pPrinterName , SHORT dmType, SHORT dmValue, VARIANT_BOOL* ret) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); CString sPrinterName(pPrinterName); (*ret) = VARIANT_TRUE; ////////////////////////////////////////////////////////////////////////// HANDLE hPrinter = NULL; DWORD dwNeeded = 0; PRINTER_INFO_2 *pi2 = NULL; DEVMODE *pDevMode = NULL; PRINTER_DEFAULTS pd; BOOL bFlag; LONG lFlag; // Open printer handle (on Windows NT, you need full-access because you // will eventually use SetPrinter)... ZeroMemory(&pd, sizeof(pd)); pd.DesiredAccess = PRINTER_ALL_ACCESS; bFlag = OpenPrinter(LPSTR(sPrinterName.operator LPCSTR()) , &hPrinter, &pd); if (!bFlag || (hPrinter == NULL)) return FALSE; // The first GetPrinter tells

마이크로스테이션 V8의 Batch Process를 이용한 Dwg 변환

이 매크로를 만들게 된 이유는 Batch Converter로 변환 시 Dgn에서 Off된 Level도 Dwg로 변환 시 모두 On이 되기 때문입니다. Dgn에서 Off된 Level를 찾아 저장 후, Dwg로 변환하고 나서 저장한 Level과 같은 이름의 Level를 찾아 Off시키도록 했습니다. - Macro File - Sub ConvertWithoutUnvisibleLevel ( ) RemoveLevel = False Dim oLevels As Levels Dim oLevel As Level Dim oView As View Dim oOffLevel ( 10 ) As String Dim counter ( 2 ) As Integer , iOffLevelCount Set oLevels = ActiveDesignFile . Levels Set oView = ActiveDesignFile . Views ( 1 ) counter ( 0 ) = 0 iOffLevelCount = 0 Do While counter ( 0 ) < oLevels . Count counter ( 0 ) = counter ( 0 ) + 1 Set oLevel = oLevels . Item ( counter ( 0 ) ) If True < > oLevel . IsDisplayedInView ( oView ) Then oOffLevel ( iOffLevelCount ) = oLevel . Name iOffLevelCount = iOffLevelCount + 1 End If Loop

이미지 파일을 알파채널을 가진 BMP 파일로 변환

아래와 같이 간단하게 할 수 있습니다. if (5 == args.Length) { string sInutFilePath = args[0]; string sOutputFilePath = args[1]; int iRed = Convert.ToInt32(args[2]); int iGreen = Convert.ToInt32(args[3]); int iBlue = Convert.ToInt32(args[4]); Bitmap bmp = Image.FromFile(sInutFilePath) as Bitmap; bmp.MakeTransparent(Color.FromArgb(iRed, iGreen, iBlue)); bmp.Save(sOutputFilePath, ImageFormat.Bmp); } else { Console.WriteLine("Usage: png2bmp32 "); }

MessageBox with custom icon

MSGBOXPARAMS msgbox = { 0 } ; msgbox . cbSize = sizeof ( msgbox ) ; msgbox . dwStyle = MB_USERICON | MB_OK ; // MB_USERICON - flag for "lpszIcon" msgbox . hInstance = GetModuleHandle ( 0 ) ; // handle of file with icon msgbox . hwndOwner = hWnd ; // parent window msgbox . lpszIcon = ( LPTSTR ) IDI_ICOID ; // ID of icon msgbox . lpszCaption = " Caption " ; msgbox . lpszText = " MessageBox with user icon " ; MessageBoxIndirect ( & msgbox ) ;

Val 함수 버그

VB는 거의 사용하지 않는데, 문의가 와서 확인을 해보니 아래와 같이 Val 함수 버그가 있었습니다. Val ( "5D1" ) 결과값을 5로 기대하겠지만 Val 함수는 50을 리턴합니다. 즉 이러한 문제를 피하기 위해 하는 수 없이 함수를 만들어 사용해야만 합니다. Function myInt ( s As String ) As Integer For i = 1 To Len ( s ) If IsAlpha ( Mid ( s , i , 1 ) ) Then Exit For End If Next If i > 1 Then s = Mid ( s , 1 , i - 1 ) End If myInt = Val ( s ) End Function Function IsAlpha ( s As String ) As Boolean Dim i As Integer Dim ch As Byte IsAlpha = True For i = 1 To Len ( s ) ch = Asc ( UCase $ ( Mid ( s , i , 1 ) ) ) If Not ( ( ch > = 65 ) And ( ch < = 90 ) ) Then IsAlpha = False Exit For End If Next i End Function --- Val 에러를 방지하는 방법 Many programmers use VB's Val() function to convert user inputted strings into numbers. This useful function returns zero (0) f

MDL(USTN J) 프로그래밍시 유의 사항

J버전용 MDL 프로그램을 개발할 때 편집기를 VS를 사용하는데, 일반적으로 MDL 소스 파일의 확장자가 .mc라 편집기에서 문법 강조가 되지 않아 확장자를 .c로 바꾸어 사용 했습니다. 지금껏 잘 사용하다가 어떤 프로그램을 개발할때 MKE 파일에서 링크가 제대로 되지 않거나, 인클루드 구문이 제대로 기능을 발휘하지 못하는 현상이 발생했습니다. 한참을 그 원인을 찾다가 확장자 때문에 그렇다는 것을 알게되었습니다. 즉 확장자를 .c에서 .mc로 바꾸면 위의 문제가 사라지는 것이었습니다. 그런데 그렇게 하면 문법 강조를 사용할 수 없다는 사소한 문제가 있습니다. VS의 메뉴를 이것저것 찾아보다가 확장자를 추가해서 문법 강조를 사용할 수 있는 방법을 찾았습니다. Tools->Options

keybd_event

도움글 keyd_event 함수를 통해서 keyboard를 이벤트를 생성할 수 있습니다. 자세한 내용은 위 도움글을 참조하시면 됩니다. void SendKeyIn ( const STRING_T & keyin ) { for ( int nIndex = 0 ; nIndex < int ( keyin . size ( ) ) ; + + nIndex ) { SHORT ch = VkKeyScan ( keyin [ nIndex ] ) ; if ( 1 = = HIBYTE ( ch ) ) { /// shift key press keybd_event ( VK_SHIFT , MapVirtualKey ( VK_SHIFT , 0 ) , 0 , 0 ) ; } keybd_event ( ch , MapVirtualKey ( keyin [ nIndex ] , 0 ) , 0 , 0 ) ; /// 0xE0 keybd_event ( ch , MapVirtualKey ( keyin [ nIndex ] , 0 ) , KEYEVENTF_KEYUP , 0 ) ; if ( 1 = = HIBYTE ( ch ) ) { /// shift key up keybd_event ( VK_SHIFT , MapVirtualKey ( VK_SHIFT , 0 ) , KEYEVENTF_KEYUP , 0 ) ; } } }

마이크로스테이션 V8의 Batch Process를 이용한 PDF 출력

마이크로스테이션 V8 의 Batch Process 를 이용한 Dgn->PDF 출력 첨부한 파일 (Command File) 을 로컬에 복사하세요 . 1.      Utility à Batch Process 를 클릭 2.      PDF 로 출력할 Dgn  파일을 추가 3.      첨부한 Command File 을 선택 4.      Batch Job 실행 5.      PDF 파일은 Adobe Acrobat 에서 설정한 Output Folder 에 생성이 됩니다 . --- Command File -- #---------------------------------------------------------------------- # #  Command file for batchprocess utility # #  This command file was originally copied from $(MS_DATA)cmdfiletemplate.txt. #  Command file information: #       - Lines that start with the '#' character are treated as comments and ignored. # #---------------------------------------------------------------------- fit view extended print attributes lineweights off # 레퍼런스등이 있을 수 있으므로 place fence allfiles 1 print boundary fence plot execute

How do you detect where two line segments intersect?

There’s a nice approach to this problem that uses vector cross products. Define the 2-dimensional vector cross product  v  ×  w  to be  v x w y  −  v y w x  (this is the magnitude of the 3-dimensional cross product). Suppose the two line segments run from  p  to  p  +  r  and from  q  to  q  +  s . Then any point on the first line is representable as  p  +  t   r  (for a scalar parameter  t ) and any point on the second line as  q  +  u   s  (for a scalar parameter  u ). The two lines intersect if we can find  t  and  u  such that: p  +  t   r  =  q  +  u   s Cross both sides with  s , getting ( p  +  t   r ) ×  s  = ( q  +  u   s ) ×  s And since  s  ×  s  =  0 , this means t ( r  ×  s ) = ( q  −  p ) ×  s And therefore, solving for  t : t  = ( q  −  p ) ×  s  / ( r  ×  s ) In the same way, we can solve for  u : u  = ( q  −  p ) ×  r  / ( r  ×  s ) Now if  r  ×  s  =  0  then the two lines are parallel. (There are two cases: if ( q  −  p ) × 

VisualStudio 재배포판 설치여부 확인하기

원문 VC 8.0 Redistributables This function detects if VC++ 8.0 redistributables are installed on the machine ;------------------------------- ; Test if Visual Studio Redistributables 2005+ SP1 installed ; Returns -1 if there is no VC redistributables intstalled Function CheckVCRedist Push $R0 ClearErrors ReadRegDword $R0 HKLM "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{7299052b-02a4-4627-81f2-1818da5d550d}" "Version"  ; if VS 2005+ redist SP1 not installed, install it IfErrors 0 VSRedistInstalled StrCpy $R0 "-1" VSRedistInstalled: Exch $R0 FunctionEnd It should be noted that the DLLs could be installed even if the redistributable isn't installed. One example would be if the user has Visual Studios installed, then they have the dlls without the redist. Newer Visual Studio runtime versions: Visual Studio 2005, x86 SP1: ( 8.0.59193) "{837b34e3-7c30-493c-8f6a-2b0f04e2912c}" Visual Studio 2008, x86 S

OpenCASCADE 6.6.0 빌드하기

1. 환경 변수 설정하기 OpenCASCADE 6.6.0은 이전 버젼과 바이너리 호환이 되지 않습니다. 따라서 이전 버젼으로 작성된 프로젝트는 소스를 다시 컴파일해야만 합니다.

도면을 PDF로 저장

SmartSketch는 도면을 PDF로 저장할 수 있는 함수를 제공하고 있습니다. void SaveAsPDF(string fileName, bool Bookmarks, PDFResolutionConstants Resolution, PDFColorModeConstants ColorMode, PDFJpegCompressionConstants JpegCompression, int SheetArraySize, object SheetArray); 다른 인자들은 쉽게 알수 있는데 제일 뒤 SheetArraySize , SheetArray가 뭔지 모호합니다. 느낌으로는 SmartSketch도 하나의 도면에 여러개의 Sheet를 가질 수 있으니, SheetArraySize는 Sheet의 갯수, SheetArray는 Sheet를 담은 배열이라 생각하고 값을 입력했더니 프로그램 오류가 발생했습니다. 그래서 궁리끝에 SheetArraySize에 0 , SheetArray에 null을 넘겨주니 에러없이 동작하였습니다. 아래는 PDF로 저장하는 예제 코드입니다. public bool SaveAsPDF(string sPDFFilePath , string sShaFilePath , ref string sLog) { var app = ComInterop.GetInstance<SmartSketch.Application>("SmartSketch.Application"); if (app != null) { try { app.Visible = true; /// Make application visible var doc = app.Documents.Open(sShaFilePath); /// Document Open doc.SaveAsPDF(sPDFFilePath, false, SmartSketch.PDFResolutionConstants.igPDFResolution1200DPI, SmartSketch.PDFColo

리스트 뷰의 응용

원문보기 1. 콜백항목 리스트 뷰는 컨트롤이 자체적으로 데이터를 관리한다. 그러나 메모리의 낭비가 생기고 데이터를 따로 관리해야 함으로 대량의 데이터를 관리할 경우에는 콜백 항목으로 데이터를 관리하는게 좋다. 콜백항목은  응용프로그램이 직접 리스트 뷰의 데이터를 소유 하고 있다가 리스트 뷰가 출력 또는 정렬을 위해 데이터가  필요할 경우에만 데이터를 제공 해 주는 형식을 말한다. 일괄적으로 데이터를 관리할 수 있다는 점과 메모리가 이중으로 낭비되지 않는다는 장점이 있다. 1-1 콜백항목의 추가 콜백항목을 사용하기 위해서는 일단 항목(아이템)을 추가 할 때 문자열은  LPSTR_TEXTCALLBACK  형식으로, 이미지는  I_IMAGECALLBACK  형식으로 추가를 하게 되면 콜백항목으로 등록이 된다. ex) LVITEM lvi ; lvi . mask = LVIF_TEXT ; lvi . state = 0 ; lvi . stateMask = 0 ; lvi . iSubItem = 0 ; for ( int i = 0 ; i < 5 ; i + + ) { lvi . iItem = i ; lvi . pszText = LPSTR_TEXTCALLBACK ; ListView_InsertItem ( hListView , & lvi ) ; ListView_SetItemText ( hListView , i , 1 , LPSTR_TEXTCALLBACK ) ; ListView_SetItemText ( hListView , i , 2 , LPSTR_TEXTCALLBACK ) ; ListView_SetItemText ( hListView , i , 3 , LPSTR_TEXTCALLBACK ) ; } 1-2 콜백항목의 데이터 처리 콜백항목으로 등록만 해서는 리스트 뷰에 데이터가 나타나지

MSTN VBA - Lession7(폴더 선택하기)

폴더를 선택하는 예제입니다. Dim MyBl As BrowseInfo Dim FList As Long Dim DirName As String Dim SelFolder As String DirName = Space(255) MyBl.sTitle = "Select Root Folder" MyBl.sDisplayName = Space(255) MyBl.ulFlags = Bif_ReturnOnlyFSDirs FList = SHBrowseForFolder(MyBl) SelFolder = SHGetPathFromIDList(FList, DirName) DirName = Left(DirName, InStr(1, DirName, Chr(0)) - 1) If DirName <> "" Then TextBoxFolder.Text = DirName Else TextBoxFolder.Text = "" End If

How to force C# .net app to run only one instance in Windows?

Single Application을 생성하는 예제입니다. [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetForegroundWindow(IntPtr hWnd); /// /// The main entry point for the application. /// [STAThread] static void Main() { bool createdNew = true; using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew)) { if (createdNew) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } else { Process current = Process.GetCurrentProcess(); foreach (Process process in Process.GetProcessesByName(current.ProcessName)) { if (process.Id != current.Id) { SetForegroundWindow(process.MainWindowHandle); break; } } } } }

Resource Compiler Error RC2170 bitmap file filename is not in 3.00 format

출처 THE IMAGINATIONS | 수나미 원문 https://blog.naver.com/imanoos/114581059 Resource Compiler Error RC2170 bitmap file filename is not in 3.00 format 매뉴얼로 PNG파일을 추가했는데 이런 에러가 떴을 경우, .rc 파일을 코드보기로 열어서 해당 파일의 BITMAP이라고 지정된 부분을 PNG로 수정하고 다시 컴파일한다. 별의별 일들이 발생한다니까요~~~

요소의 잘못된 Range 수정하기

특정 요소의 Range가 잘못된 경우가 발생할 수 있습니다. 특히 3rd party 프로그램에서 생성된 파일일 경우.. 이때 Range를 수정하는 명령이 있습니다. mdl load fixrange filedesign 특정 폴더 안의 도면에 대해서 위 명령을 수행하는 매크로를 만들어 보겠습니다. Sub main() Dim S$ Dim One_File_List as String MbeSendCommand "mdl load fixrange" One_File_List = Dir$("C:\Temp" + "\*.*") Do While One_File_List <> "" MbeSendCommand "newfile " + One_File_List$ MbeSendCommand "filedesign" One_File_List = Dir$ Loop Close 'up to here End Sub

Polygon 해칭

주어진 정점으로 이루어진 Polygon을 해칭하는 예제입니다. inData는 "HATCHPLINE,0,0,0.1,0,0.1,0.1,0,0.1,0,0," 이런식으로 주어지면 됩니다. Private Sub drawHatchPline(ByVal inData As String) Dim m_oShapeElement As ShapeElement Dim m_Points() As Point3d Dim ptrn As CrossHatchPattern Dim vertices() As Point3d Dim tokens() As String Dim i As Integer, index As Integer index = 0 tokens = Split(inData, ",") ReDim Preserve m_Points(UBound(tokens) / 2) For i = 1 To UBound(tokens) m_Points(index) = Point3dFromXY(Val(tokens(i)), Val(tokens(i + 1))) i = i + 1 index = index + 1 Next Set m_oShapeElement = CreateShapeElement1(msv8Element, m_Points, msdFillModeNotFilled) ActiveModelReference.AddElement m_oShapeElement ' Use a CrossHatchPattern object to set up the parameters for ' the hatching operation. Set ptrn = CreateCrossHatchPattern(0.01, 0.01, Pi / 4, -Pi / 4) ver