2012년 11월 12일 월요일

VB6 mciwndx.ocx (MCI Control)


1. MCIWNDX.OCX는 멀티미디어(WAV , AVI , Video ,기타자료)콘트롤로서 Multimedia API 함수인 mciSendCommand()를 통하여 제어 할 수 있다.

2.언어의 문제를 피하기 위하여 mciSendCommand 를 이용하여 사용한다.

Example>
1.Visual Basic 시작

2.MCIWNDX.ocx를 프로젝트에 추가

3.새로운 Module (Module1)을 프로젝트에 추가. General declarations section에 선언

Global Const MCI_STATUS = &H814
Global Const MCI_STATUS_ITEM = &H100&
Global Const MCI_STATUS_MODE = &H4&
Global Const MCI_STRING_OFFSET = 512
Global Const MCI_MODE_NOT_READY = (MCI_STRING_OFFSET + 12)
Global Const MCI_MODE_STOP = (MCI_STRING_OFFSET + 13)
Global Const MCI_MODE_PLAY = (MCI_STRING_OFFSET + 14)
Global Const MCI_MODE_RECORD = (MCI_STRING_OFFSET + 15)
Global Const MCI_MODE_SEEK = (MCI_STRING_OFFSET + 16)
Global Const MCI_MODE_PAUSE = (MCI_STRING_OFFSET + 17)
Global Const MCI_MODE_OPEN = (MCI_STRING_OFFSET + 18)
Type MCI_STATUS_PARMS
     dwCallback As Long
     dwReturn As Long
     dwItem As Long
     dwTrack As Long
End Type
Declare Function mciSendCommand Lib "mmsystem" _
        (ByVal udeviceid As Integer, ByVal uMessage As Integer, _
         ByVal dwParam1 As Long, dwParam2 As Any) As Long
        
4.아래 function을 module에 추가

Function GetMCIWndxMode(MCIControl As MCIWnd) As Long
     Dim Info As MCI_STATUS_PARMS
     Dim Ret As Long
     Info.dwItem = MCI_STATUS_MODE
     Info.dwCallback = 0
     Info.dwTrack = 0

     Ret = mciSendCommand(MCIControl.DeviceID,MCI_STATUS,MCI_STATUS_ITEM,Info)
     GetMCIWndxMode = Info.dwReturn
End Function

5.command button (Command1)과 MCIWNDX control (MCIWnd1) 을 Form1에 추가.

6.Command1버튼에 아래와 같은 code를 입력.

Sub Command1_Click ()
     Dim status As Long
     ' 아래의 Avi file을 사용자가 임의의 file을 지정
     MCIWnd1.Filename = "c:\winnt35\clock.avi"
      ' 상태를 알아낸다
     status = GetMCIWndxMode(MCIWnd1)
     If status = MCI_MODE_STOP Then   ' is it playing or stopped
          Print "stopped"
     End If
End Sub

2012년 11월 5일 월요일

VB6 API 이용 외부 프로그램 실행 - 동기적 실행

API 함수 및 상수를 많이 이용한다.

※동기적 실행이란 다른 프로그램 종료시까지 대기를 한 후,
   끝남과 동시에 다음 코딩라인으로 넘어가면서 실행된다는 뜻.

선언부 ↓
========================================================================
Public Type STARTUPINFO
    cb As Long
    lpReserved As String
    lpDesktop As String
    lptitle As String
    dwX As Long
    dwY As Long
    dwXSize As Long
    dwYSize As Long
    dwXCountChars As Long
    dwYCountChars As Long
    dwFillAttribute As Long
    dwFlags As Long
    wShowWindow As Integer
    cbReserved2 As Integer
    lpReserved2 As Long
    hStdInput As Long
    hStdOutput As Long
    hStdError As Long
End Type


Public Type PROCESS_INFORMATION
    hProcess As Long
    hThread As Long
    dwProcessID As Long
    dwThreadID As Long
End Type



' API함수 선언
Public Declare Function WaitForSingleObject Lib "kernel32" _
              (ByVal hHandle As Long, _
               ByVal dwMilliseconds As Long) As Long

Public Declare Function CreateProcess Lib "kernel32" Alias "CreateProcessA" _
              (ByVal lpApplicationName As Long, _
               ByVal lpCommandLine As String, _
               ByVal lpProcessAttributes As Long, _
               ByVal lpThreadAttributes As Long, _
               ByVal bInheritHandles As Long, _
               ByVal dwCreationFlags As Long, _
               ByVal lpEnvironment As Long, _
               ByVal lpCurrentDriectory As Long, _
               lpStartupInfo As STARTUPINFO, _
               lpProcessInformation As PROCESS_INFORMATION) As Long

Public Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long


' API함수 상수선언
Public Const NORMAL_PRIORITY_CLASS = &H20&
Public Const INFINITE = -1&
Public Const STARTF_USESHOWWINDOW = &H1
Public Const SW_SHOWMINIMIZED = 2
Public Const SW_SHOWMAXIMIZED = 3
Public Const SW_SHOWMINNOACTIVE = 7
Public Const SW_SHOWDEFAULT = 10



' Shell 명령을 실행시킨 후 해당 Shell이 완전히 종료될 때까지 대기하는 함수
Public Sub RunAndWait(RunCommand As String)
    Dim vProc As PROCESS_INFORMATION
    Dim vStart As STARTUPINFO
    Dim vRv As Long

    vStart.cb = LenB(RunCommand)
    vStart.dwFlags = STARTF_USESHOWWINDOW
    vStart.wShowWindow = SW_SHOWDEFAULT 'SW_SHOWMAXIMIZED

    ' Process 실행   
    vRv = CreateProcess(0&, RunCommand, 0&, 0&, 1&, NORMAL_PRIORITY_CLASS, 0&, 0&, vStart, vProc)
    Screen.ActiveForm.MousePointer = 11
    DoEvents

    ' 대기    vRv = WaitForSingleObject(vProc.hProcess, INFINITE)
    Screen.ActiveForm.MousePointer = 0
    DoEvents
    ' Process 종료    vRv = CloseHandle(vProc.hProcess)
End Sub

========================================================================

폼에 버튼 생성 후 다음과 같이 코딩

 Private Sub Command1_Click()
    RunAndWait "c:\windows\notepad.exe"
    MsgBox "메모장이 종료되었습니다."
End Sub

Public Function WinExecAndWait(strExecFile As String) As Long
    Dim WshShell As Object
    ''strExecFile = "c:\windows\notepad.exe"   실행파일 PullPath
   
    Set WshShell = CreateObject("Wscript.Shell")
    Call WshShell.Run(strExecFile, 1, 1)
End Function

VB6 Shell API 이용 외부 프로그램 실행 - 비동기적 실행

API 함수

Declare Function ShellExecute Lib "shell32.dll"  Alias "ShellExecuteA" _
    (ByVal hWnd As Long, ByVal lpOperation As String, _
     ByVal lpFile As String, ByVal lpParameters As String, _
     ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

외부 파일 실행과 파라미터 지정

Call ShellExecute(0, "Open", strFilePath, strParms, strDir, 5)
예제>
아크로뱃 리더를 이용해서 D:\의 sample.pdf 열기

call shellexecute(0, "Open", "C:\Program Files\Adobe\Acrobat 7.0\Reader\AcroRd32.exe", "D:\sample.pdf", "D:\", 5)

VB6 Shell을 이용한 외부프로그램 단순 실행 - 비동기적 실행

형식

shell ("[파일위치]", [포커스(쉼표찍으면 메소드 찍는목록 나옴-프로그램 켰을때 활성화 시킬지 최소화 시킬지등 창 상태 정하기])
만약에 계산기가 c:\windows\System32\calc.exe 에 있다면 다음과 같이 삽입

Shell ("C:\WINDOWS\System32\calc.exe")

VB6 strConv Function

바이트 단위 전문 data를 주고받을 때 필요한 Option들

함수 형식
Function StrConv(String, Conversion As VbStrConv, [LocaleID As Long])
1. String
  변환하고자 하는 문자열

2. Conversion As VbStrConv
  변환하고자 하는 형식을 지정.
  Conversion 다음에 As VbStrConv라고 되어있는데 VbStrConv형으로 미리 선언되어 있단 뜻.
  VbStrConv는 VB자체에서 이미 정의되어 있는 상수이며 그 종류는 다음과 같다.

상수명상수값설명 
Const vbFromUnicode128 (&H80)유니코드에서 기본코드로 변환
Const vbHiragana32 (&H20)Katakana를 Hirakana로 변환(일본만 해당)
Const vbKatakana 16 (&H10)Hirakana를 Katakana로 변환(일본만 해당)
Const vbLowerCase2문자열을 소문자로 변환
Const vbNarrow82바이트 문자를 1바이트로 변환
Const vbProperCase3문자열내 첫글자를 대문자로 변환
Const vbUnicode64 (&H40)기본코드에서 유니코드로 변환
Const vbUpperCase1문자열을 대문자로 변환
Const vbWide41바이트 문자를 2바이트로 변환



예) 텍스트 박스와 버튼 컨트롤 추가 후 어떻게 바뀌는지 보면 간단함

Private Sub Command1_Click()
    MsgBox StrConv(Text1.Text, vbFromUnicode)
    ''MsgBox StrConv(Text1.Text, vbHiragana) ''// 기본코드가 일본어가 아닐 경우 에러
    ''MsgBox StrConv(Text1.Text, vbKatakana) ''// 기본코드가 일본어가 아닐 경우 에러
    MsgBox StrConv(Text1.Text, vbLowerCase)
    MsgBox StrConv(Text1.Text, vbNarrow)
    MsgBox StrConv(Text1.Text, vbProperCase)
    MsgBox StrConv(Text1.Text, vbUnicode)
    MsgBox StrConv(Text1.Text, vbUpperCase)
    MsgBox StrConv(Text1.Text, vbWide)
End Sub

VB6 Microsoft Excel Automation

1.표준 EXE 프로젝트
2.프로젝트 참조→"Microsoft Excel 10.0 Object Library" 항목 선택하여 (Excel 2002에 대한 참조)
  이 항목이 목록에 나타나지 않으면 Excel 2002가 제대로 설치되어 있는지 확인
참고> Microsoft Office Excel 2003을 자동화하는 경우 형식 라이브러리는 참조 목록에 "Microsoft Excel 11.0 Object Library"로 표시
      Microsoft Excel 2000을 자동화하는 경우에는 형식 라이브러리가 참조 목록에 "Microsoft Excel 9.0 Object Library"로 표시
      Microsoft Excel 97의 경우에는 "Microsoft Excel 8.0 Object Library"로 표시
3.Form1에 CommandButton을 추가.
4.Form1의 코드 창에서 다음 코드를 삽입.


 Option Explicit
  
   Private Sub Command1_Click()
      Dim oXL As Excel.Application
      Dim oWB As Excel.Workbook
      Dim oSheet As Excel.Worksheet
      Dim oRng As Excel.Range
     
      'On Error GoTo Err_Handler
     
   ' Start Excel and get Application object. - 오브젝트 설정
      Set oXL = CreateObject("Excel.Application")
      oXL.Visible = True
     
   ' Get a new workbook. - 새로운 워크북 생성 (이게 하나의 파일임)
      Set oWB = oXL.Workbooks.Add
      Set oSheet = oWB.ActiveSheet      (새로운 워크시트 오브젝트지정)
     
   ' Add table headers going cell by cell. - 셀에 이름을 쓴다.
      oSheet.Cells(1, 1).Value = "First Name"
      oSheet.Cells(1, 2).Value = "Last Name"
      oSheet.Cells(1, 3).Value = "Full Name"
      oSheet.Cells(1, 4).Value = "Salary"
     
   ' Format A1:D1 as bold, vertical alignment = center.
      With oSheet.Range("A1", "D1")
         .Font.Bold = True
         .VerticalAlignment = xlVAlignCenter
      End With
     
   ' Create an array to set multiple values at once.
      Dim saNames(5, 2) As String
      saNames(0, 0) = "John"
      saNames(0, 1) = "Smith"
      saNames(1, 0) = "Tom"
      saNames(1, 1) = "Brown"
      saNames(2, 0) = "Sue"
      saNames(2, 1) = "Thomas"
      saNames(3, 0) = "Jane"
      saNames(3, 1) = "Jones"
      saNames(4, 0) = "Adam"
      saNames(4, 1) = "Johnson"
     
    ' Fill A2:B6 with an array of values (First and Last Names).
      oSheet.Range("A2", "B6").Value = saNames
     
    ' Fill C2:C6 with a relative formula (=A2 & " " & B2).
      Set oRng = oSheet.Range("C2", "C6")
      oRng.Formula = "=A2 & "" "" & B2"
     
    ' Fill D2:D6 with a formula(=RAND()*100000) and apply format.
      Set oRng = oSheet.Range("D2", "D6")
      oRng.Formula = "=RAND()*100000"
      oRng.NumberFormat = "$0.00"
     
    ' AutoFit columns A:D.
      Set oRng = oSheet.Range("A1", "D1")
      oRng.EntireColumn.AutoFit
     
    ' Manipulate a variable number of columns for Quarterly Sales Data.
      Call DisplayQuarterlySales(oSheet)
     
    ' Make sure Excel is visible and give the user control
    ' of Microsoft Excel's lifetime.
      oXL.Visible = True
      oXL.UserControl = True
     
    ' Make sure you release object references.
      Set oRng = Nothing
      Set oSheet = Nothing
      Set oWB = Nothing
      Set oXL = Nothing
     
   Exit Sub
   Err_Handler:
      MsgBox Err.Description, vbCritical, "Error: " & Err.Number
   End Sub
  
   Private Sub DisplayQuarterlySales(oWS As Excel.Worksheet)
      Dim oResizeRange As Excel.Range
      Dim oChart As Excel.Chart
      Dim iNumQtrs As Integer
      Dim sMsg As String
      Dim iRet As Integer
     
    ' Determine how many quarters to display data for.
      For iNumQtrs = 4 To 2 Step -1
         sMsg = "Enter sales data for" & Str(iNumQtrs) & " quarter(s)?"
         iRet = MsgBox(sMsg, vbYesNo Or vbQuestion _
            Or vbMsgBoxSetForeground, "Quarterly Sales")
         If iRet = vbYes Then Exit For
      Next iNumQtrs
     
      sMsg = "Displaying data for" & Str(iNumQtrs) & " quarter(s)."
      MsgBox sMsg, vbMsgBoxSetForeground, "Quarterly Sales"
     
    ' Starting at E1, fill headers for the number of columns selected.
      Set oResizeRange = oWS.Range("E1", "E1").Resize(ColumnSize:=iNumQtrs)
      oResizeRange.Formula = "=""Q"" & COLUMN()-4 & CHAR(10) & ""Sales"""
     
    ' Change the Orientation and WrapText properties for the headers.
      oResizeRange.Orientation = 38
      oResizeRange.WrapText = True
     
    ' Fill the interior color of the headers.
      oResizeRange.Interior.ColorIndex = 36
     
    ' Fill the columns with a formula and apply a number format.
      Set oResizeRange = oWS.Range("E2", "E6").Resize(ColumnSize:=iNumQtrs)
      oResizeRange.Formula = "=RAND()*100"
      oResizeRange.NumberFormat = "$0.00"
     
    ' Apply borders to the Sales data and headers.
      Set oResizeRange = oWS.Range("E1", "E6").Resize(ColumnSize:=iNumQtrs)
      oResizeRange.Borders.Weight = xlThin
     
    ' Add a Totals formula for the sales data and apply a border.
      Set oResizeRange = oWS.Range("E8", "E8").Resize(ColumnSize:=iNumQtrs)
      oResizeRange.Formula = "=SUM(E2:E6)"
      With oResizeRange.Borders(xlEdgeBottom)
         .LineStyle = xlDouble
         .Weight = xlThick
      End With
     
    ' Add a Chart for the selected data
      Set oResizeRange = oWS.Range("E2:E6").Resize(ColumnSize:=iNumQtrs)
      Set oChart = oWS.Parent.Charts.Add
      With oChart
         .ChartWizard oResizeRange, xl3DColumn, , xlColumns
         .SeriesCollection(1).XValues = oWS.Range("A2", "A6")
            For iRet = 1 To iNumQtrs
               .SeriesCollection(iRet).Name = "=""Q" & Str(iRet) & """"
            Next iRet
         .Location xlLocationAsObject, oWS.Name
      End With
     
    ' Move the chart so as not to cover your data.
      With oWS.Shapes("Chart 1")
         .Top = oWS.Rows(10).Top
         .Left = oWS.Columns(2).Left
      End With
     
    ' Free any references.
      Set oChart = Nothing
      Set oResizeRange = Nothing
  
   End Sub

VB6 Binary File Reading TEST

1. Form을 하나 만든다.
2. Data 라는 FlexGrid를 추가
3. CmdBinary 와 CmdRead 라는 Button 컨트롤 추가
4.

Option Explicit

Private Sub CmdBinary_Click()
    Dim fn As Integer
    Dim strFile As String
    Dim strTxt As String
    strFile = App.Path & "\C111118A_YP_T-CAR_NCAP.R64"
    fn = FreeFile
  
    Dim arrBytes() As Byte
    ReDim arrBytes(FileLen(strFile))
    Open strFile For Binary As #fn
   
    Dim mystring As String
    mystring = Space(LOF(fn))
   
    If Not EOF(fn) Then
        Get #fn, , arrBytes
        Get #fn, , mystring
        'mystring = StrConv(arrBytes, vbUnicode)
    End If
  
    Close #fn
   
    Dim j As String
    If InStr(StrConv(arrBytes, vbUnicode), Chr(0)) Then
         j = Left(StrConv(arrBytes, vbUnicode), InStr(StrConv(arrBytes, vbUnicode), Chr(0)) - 1)
        Txt1.Text = j
    End If
   
    Dim i As Integer
    With Data
        .ScrollTrack = True
        .Cols = 4
        .ColAlignment(0) = flexAlignCenterCenter
        .ColAlignment(1) = flexAlignCenterCenter
        .ColAlignment(2) = flexAlignCenterCenter
        .Rows = 15000
        .TextMatrix(0, 1) = "arrBytes"
        For i = 1 To .Rows - 1
            .TextMatrix(i, 0) = i
            .TextMatrix(i, 1) = arrBytes(i - 1)
            .TextMatrix(i, 2) = StrConv(arrBytes(i - 1), vbUnicode)
            .TextMatrix(i, 3) = Chr(arrBytes(i - 1))
        Next
    End With
   
   
     'Txt1.Text = mystring
End Sub


Private Sub CmdRead_Click()
    Dim filenum As Integer
    filenum = FreeFile
    Open App.Path & "\C120823B.R64" For Binary As filenum
   
    Dim BytePosition As Long
    Dim StringSize As Long
    Dim GetString As String
    Dim intTemp As Integer
   
    '자료 크기만큼 메모리 할당
    GetString = String(8, " ") 'StringSize, " ")
   
    Get filenum, 80, GetString
    Txt1.Text = StrConv(GetString, vbUnicode)
       
    Close filenum
End Sub