Option Strict Off
Option Explicit On
'名前空間を定義　----------------------
Imports System.Runtime.InteropServices
Imports VB = Microsoft.VisualBasic
Imports System.IO

Namespace VB_sample

#Region "コールバック関数デリゲート宣言　古"
    Delegate Function CommEventDelegate(ByVal iPortNo As Short, ByVal lBufferLen As Integer, ByVal lEvent As Integer, ByVal pParam As Integer) As Short
    Delegate Function ResponseEventDelegate(ByVal iPortNo As Short, ByVal lEvent As Integer, ByVal lpData As String, ByVal iDataLen As Short, ByVal pParam As Integer) As Short
    Delegate Function ReceiveDataBCCEventDelegate(ByVal iPortNo As Short, ByVal lEvent As Integer, ByVal lpData As String, ByVal iDataLen As Short, ByVal pParam As Integer) As Short
#End Region '"コールバック関数デリゲート宣言"

#Region "コールバック関数デリゲート宣言 新"
    ''' <summary> 
    ''' レスポンス受信イベントハンドラ登録 コールバック関数デリゲート宣言
    ''' </summary> 
    Public Delegate Function CallBack( _
        ByVal iPortNo As Short, _
        ByVal lEvent As Integer, _
        ByVal lpData As IntPtr, _
        ByVal iDataLength As Short, _
        ByVal pParem As Integer) As Short
    ''' <summary> 
    ''' 通信イベントハンドラ登録 コールバック関数デリゲート宣言
    ''' </summary> 
    Public Delegate Function CallBack3( _
         ByVal iPortNo As Short, _
         ByVal lBufferLength As Integer, _
         ByVal lEvent As Integer, _
         ByVal pParam As Integer) As Short
    ''' <summary> 
    ''' 電文データ受信イベントハンドラ登録 コールバック関数デリゲート宣言
    ''' </summary> 
    Public Delegate Function CallBack4( _
        ByVal iPortNo As Short, _
        ByVal lEvent As Integer, _
        ByVal lpData As IntPtr, _
        ByVal iDataLength As Short, _
        ByVal pParem As Integer) As Short
#End Region

    Friend Class Form1

#Region "デリゲートクラス変数宣言"

        Inherits System.Windows.Forms.Form
        Private CommEventCallBack As CommEventDelegate 'CommEven用
        Public ResponseEventCallBack As ResponseEventDelegate 'ResponseEvent用
        Public ReceiveDataBCCEventCallBack As ReceiveDataBCCEventDelegate 'ReceiveDataBCCEvent用

        ' レスポンス受信イベントハンドラ登録 コールバック関数デリゲート
        Public myCallBack As CallBack
        ' 通信イベントハンドラ登録 コールバック関数デリゲート
        Public myCallBack3 As CallBack3
        ' 電文データ受信イベントハンドラ登録 コールバック関数デリゲート
        Public myCallBack4 As CallBack4


#End Region '"デリゲートクラス変数宣言"

#Region "Windows Kernel API宣言"
        ' メモリコピー
        Declare Sub MoveMemory Lib "kernel32" Alias "RtlMoveMemory" (ByVal Destination As Integer, ByVal Source As Integer, ByVal Length As Integer)
#End Region

#Region "アンマネージド関数定義(PCardRW64.dll)"

        'シリアルポート名取得関数 crwGetPortNames()"
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwGetPortNames( _
            ByRef bpPortNames As IntPtr, _
            ByRef piNumOfPort As Short) As Boolean
        End Function

        'COMポート情報取得関数(crwGetComDevInfo)
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwGetComDevInfo( _
            ByVal iPortNo As Short, _
            ByRef bpDriveDesc As IntPtr, _
            ByRef bpProviderName As IntPtr, _
            ByRef bpDriveDate As IntPtr, _
            ByRef bpDriverVersion As IntPtr) As Boolean
        End Function

        'ポートオープン関数(crwOpenPort)
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwOpenPort( _
            ByVal iPortNo As Short, _
            ByVal lBaudRate As Integer, _
            ByVal lpDataBit As String, _
            ByVal lpParity As String) As Short
        End Function

        'ポートクローズ関数(crwClosePort)
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwClosePort( _
            ByVal iPortNo As Short) As Short
        End Function

        'コマンド送受信関数
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwSendCommandRR( _
            ByVal iPortNo As Short, _
            ByVal iRecMode As Short, _
            ByVal lTimeOut As Integer, _
            ByVal lBusyTimeOut As Integer, _
            ByVal iDSRCheck As Short, _
            ByVal lpCommandCode As String, _
            ByVal lpCommandParameter As String, _
            ByVal iParameterLength As Short, _
            ByRef bpCOMSTS As IntPtr, _
            ByRef bpERRSEN As IntPtr, _
            ByRef bpResDATA As IntPtr) As Short
        End Function

        'コマンド送信関数
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwSendCommand( _
            ByVal iPortNo As Short, _
            ByVal lTimeOut As Integer, _
            ByVal DSRCheck As Short, _
            ByVal lpCommandCode As String, _
            ByVal lpCommandParameter As String, _
            ByVal iParameterLength As Short) As Short
        End Function

        'レスポンス受信関数
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwReceiveResponse( _
            ByVal iPortNo As Short, _
            ByVal iRecMode As Short, _
            ByVal lTimeOut As Integer, _
            ByVal iDSRCheck As Short, _
            ByRef bpCOMSTS As IntPtr, _
            ByRef bpERRSEN As IntPtr, _
            ByRef bpResDATA As IntPtr) As Short
        End Function

        'データ送信関数(応答あり)
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwSendDataWR( _
            ByVal iPortNo As Short, _
            ByVal lTimeOut As Integer, _
            ByVal iDSRCheck As Short, _
            ByVal lpData As IntPtr, _
            ByVal iDataLength As Short) As Short
        End Function

        'データ送信関数(応答なし)
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwSendDataQR( _
            ByVal iPortNo As Short, _
            ByVal lTimeOut As Integer, _
            ByVal iDSRCheck As Short, _
            ByVal lpData As IntPtr, _
            ByVal iDataLength As Short) As Short
        End Function

        'データ受信関数
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwReceiveData( _
            ByVal iPortNo As Short, _
            ByVal iDSRCheck As Short, _
            ByRef bpResDATA As IntPtr, _
            ByRef piDataLength As Short) As Short
        End Function

        '電文データ送受信関数
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwSendDataRR( _
            ByVal iPortNo As Short, _
            ByVal iRetryCount As Short, _
            ByVal lTimeOut As Integer, _
            ByVal iDSRCheck As Short, _
            ByVal lpData As IntPtr, _
            ByVal iDataLength As Short, _
            ByRef bpResDATA As IntPtr, _
            ByRef piDataLength As Short) As Short
        End Function

        '電文データ送信関数
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwSendDataBCC( _
            ByVal iPortNo As Short, _
            ByVal iACKCheck As Short, _
            ByVal iRetryCount As Short, _
            ByVal lTimeOut As Integer, _
            ByVal iDSRCheck As Short, _
            ByVal lpData As IntPtr, _
            ByVal iDataLength As Short) As Short
        End Function

        '電文データ受信関数
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwReceiveDataBCC( _
            ByVal iPortNo As Short, _
            ByVal iACKResponse As Short, _
            ByVal lTimeOut As Integer, _
            ByVal iDSRCheck As Short, _
            ByRef bpResDATA As IntPtr, _
            ByRef piDataLength As Short) As Short
        End Function

        '受信バッファークリア関数
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwComRXBufferClear( _
            ByVal iPortNo As Short) As Boolean
        End Function

        ' コマンド送受信関数
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwSendBinaryCommandRR( _
            ByVal iPortNo As Short, _
            ByVal lTimeout As Integer, _
            ByVal iRetryCount As Short, _
            ByVal iDSRCheck As Short, _
            ByVal iCTSCheck As Short, _
            ByVal lpSendData As Byte(), _
            ByVal iSendDataLength As Integer, _
            ByVal pTimeOut As Integer, _
            ByVal lpReceiveData As IntPtr, _
            ByVal iReceiveDataLength As Short, _
            ByRef piDataLengthReceived As Short) As Short
        End Function

        'バイナリデータ送信関数QR
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwSendBinaryDataQR( _
            ByVal iPortNo As Short, _
            ByVal lTimeOut As Integer, _
            ByVal iDSRCheck As Short, _
            ByVal iCTSCheck As Short, _
            ByVal lpData As Byte(), _
            ByVal iDataLength As Short) As Short
        End Function

        ' バイナリデータ受信関数
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwReceiveBinaryData( _
            ByVal iPortNo As Short, _
            ByVal lTimeOut As Integer, _
            ByVal iDSRCheck As Short, _
            ByVal lpData As IntPtr, _
            ByVal iDataLength As Short, _
            ByRef piDataLength As Short) As Short
        End Function

        ' レスポンス受信イベントハンドラ登録関数
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwSetResponseEventProc( _
            ByVal iPortNo As Short, _
            ByVal iRecMode As Short, _
            ByVal lTimeOut As Integer, _
            ByVal pResponseEventProc As ResponseEventDelegate, _
            ByVal pParam As Integer, _
            ByVal lEvent As Integer) As Short
        End Function

        ' 電文データ受信イベントハンドラ登録関数
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwSetReceiveDataBCCEventProc( _
            ByVal iPortNo As Short, _
            ByVal iACKResponse As Short, _
            ByVal lTimeOut As Integer, _
            ByVal pReceiveBCCEventProc As ReceiveDataBCCEventDelegate, _
            ByVal pParam As Integer, _
            ByVal lEvent As Integer) As Short
        End Function

        ' 通信イベントハンドラ登録関数
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwSetCommEventProc( _
            ByVal iPortNo As Short, _
            ByVal pCommEventProc As CommEventDelegate, _
            ByVal pParam As Integer, _
            ByVal lEvent As Integer) As Short
        End Function

        ' 通信中DSR/CTS信号監視設定関数
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwComDSRCTSsw( _
           ByVal iPortNo As Short, _
           ByVal iDSRCheck As Short, _
           ByVal iCTSCheck As Short) As Short
        End Function

        ' IB Image Data 作成＆出力関数 
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwIBBinarySend( _
            ByVal iPortNo As Short, _
            ByVal iRetryCount As Short, _
            ByVal iDSRCheck As Short, _
            ByVal iCTSCheck As Short, _
            ByVal iWidth As Short, _
            ByVal iHeith As Short, _
            ByVal iStartX As Short, _
            ByVal lTimeOut As Integer, _
            ByVal lComBufferSize As Integer, _
            ByVal strPathFileName As String, _
            ByRef COMSTS As IntPtr, _
            ByRef ERRSEN As IntPtr) As Short
        End Function

        ' PI Image Data 作成＆出力関数 
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwPIDataSend( _
            ByVal iPortNo As Short, _
            ByVal iRetryCount As Short, _
            ByVal iDSRCheck As Short, _
            ByVal iCTSCheck As Short, _
            ByVal iWidth As Short, _
            ByVal iHeith As Short, _
            ByVal iStartX As Short, _
            ByVal iStartY As Short, _
            ByVal lTimeOut As Integer, _
            ByVal lComBufferSize As Integer, _
            ByVal strPathFileName As String, _
            ByRef COMSTS As IntPtr, _
            ByRef ERRSEN As IntPtr) As Short
        End Function

        ' 文字コード変換関数 
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwCharCodeConv( _
            ByVal lConvMode As Short, _
            ByVal csQConvStr As String) As IntPtr
        End Function

        ' JIS／Shift-JIS漢字コード変換
        <DllImport("PCardRW64.dll")> _
        Private Shared Function crwJISconvSJIS( _
            ByVal iJConvMode As Short, _
            ByVal csQConvStr As String) As IntPtr
        End Function
#End Region

#Region "BSTR変換"
        <DllImport("OleAut32.dll", CharSet:=CharSet.Ansi, ExactSpelling:=True)> _
        Private Shared Function SysAllocStringByteLen(ByVal sz As String, ByVal len As Int32) As IntPtr
        End Function
        <DllImport("OleAut32.dll", CharSet:=CharSet.Ansi, ExactSpelling:=True)> _
        Private Shared Function SysStringByteLen(ByVal bstr As IntPtr) As Int32
        End Function
        <DllImport("OleAut32.dll", CharSet:=CharSet.Ansi, ExactSpelling:=True)> _
        Private Shared Function SysFreeString(ByVal bstr As IntPtr) As Int32
        End Function
        <DllImport("Kernel32.dll", CharSet:=CharSet.Ansi, ExactSpelling:=True)> _
        Private Shared Function lstrlenA(ByVal sz As String) As Int32
        End Function
        ''' <summary>
        ''' String型からBSTR型へ変更します。
        ''' </summary>
        ''' <param name="str">変換対象のString型の文字列を指定します。</param>
        ''' <returns>変換によって生成されたBSTR型の文字列を返します。</returns>
        ''' <remarks>生成されるBSTR型文字列のコードはANSIです。
        ''' strにNothingが渡された場合、空文字が渡されたものとして扱います。</remarks>
        Private Shared Function ConvertStringToAnsiBSTR(ByVal str As String) As IntPtr
            If str Is Nothing Then
                str = String.Empty
            End If
            Return SysAllocStringByteLen(str, lstrlenA(str))
        End Function 'ConvertStringToAnsiBSTR

        ''' <summary>
        ''' BSTR型からString型へ変更します。
        ''' </summary>
        ''' <param name="bstr">変換対象のBSTR型の文字列を指定します。</param>
        ''' <returns>変換によって生成されたString型の文字列を返します。</returns>
        ''' <remarks>bstrに指定する文字列はANSIコードとしてください。
        ''' bstrにIntPtr.Zeroが渡された場合、Nothingではなく空文字を返します。</remarks>
        Private Shared Function ConvertAnsiBSTRToString(ByVal bstr As IntPtr) As String
            If bstr = IntPtr.Zero Then
                Return String.Empty
            End If
            Return Marshal.PtrToStringAnsi(bstr, SysStringByteLen(bstr))
        End Function 'ConvertAnsiBSTRToString

        ''' <summary>
        ''' BSTR型の文字列を解放します。
        ''' </summary>
        ''' <param name="bstr">解放対象のBSTR型の文字列を指定します。</param>
        ''' <returns>解放が成功した場合はTrueを、それ以外の場合はFalseを返します。</returns>
        ''' <remarks></remarks>
        Public Shared Function DeleteAnsiBSTR(ByVal bstr As IntPtr) As Boolean
            Return 0 <= SysFreeString(bstr)
        End Function
#End Region

#Region "アンマネージドバッファ操作"
        <DllImport("KERNEL32.DLL", EntryPoint:="RtlMoveMemory", SetLastError:=True, _
            ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
        Private Overloads Shared Sub RtlMoveMemory(ByVal Destination As IntPtr, ByVal Source As IntPtr, _
            ByVal Length As UInteger)
        End Sub
        <DllImport("KERNEL32.DLL", EntryPoint:="RtlMoveMemory", SetLastError:=True, _
            ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
        Private Overloads Shared Sub RtlMoveMemory(ByVal Destination As Byte(), ByVal Source As Byte(), _
            ByVal Length As UInteger)
        End Sub
        <DllImport("KERNEL32.DLL", EntryPoint:="RtlMoveMemory", SetLastError:=True, _
            ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
        Private Overloads Shared Sub RtlMoveMemory(ByVal Destination As IntPtr, ByVal Source As Byte(), _
            ByVal Length As UInteger)
        End Sub
        <DllImport("KERNEL32.DLL", EntryPoint:="RtlMoveMemory", SetLastError:=True, _
            ExactSpelling:=True, CallingConvention:=CallingConvention.StdCall)> _
        Private Overloads Shared Sub RtlMoveMemory(ByVal Destination As Byte(), ByVal Source As IntPtr, _
            ByVal Length As UInteger)
        End Sub
        ''' <summary>
        ''' バイト列をアンマネージドバッファに変換します。
        ''' </summary>
        ''' <param name="value">変換対象のバイト列を指定します。</param>
        ''' <returns>変換によって生成されたアンマネージドバッファのポインタを返します。</returns>
        ''' <remarks>この操作によってアンマネージドヒープ上にバッファが確保されます。</remarks>
        Private Overloads Shared Function ByteArrayToUnmanagedBuffer(ByVal value As Byte()) As IntPtr
            If (value Is Nothing) Then
                Return IntPtr.Zero
            End If
            'アンマネージドヒープにバッファを確保します。
            Dim buff As IntPtr = Marshal.AllocHGlobal(value.Length + 1)
            'バイト列を確保したバッファにコピーします。
            RtlMoveMemory(buff, value, CUInt(value.Length))
            'ヌル終端文字をコピーします。
            RtlMoveMemory(CType(buff.ToInt32 + value.Length, IntPtr), New Byte(0) {}, 1)
            Return buff
        End Function

        ''' <summary>
        ''' アンマネージドバッファをバイト列に変換します。
        ''' </summary>
        ''' <param name="value">変換対象のアンマネージドバッファのポインタを指定します。</param>
        ''' <param name="Length">変換対象のアンマネージドバッファの長さを指定します。</param>
        ''' <returns>変換によって生成されたバイト列を返します。</returns>
        ''' <remarks>この操作によってvalueに指定されたアンマネージドバッファは解放され、valueにはIntPtr.Zeroが代入されます。</remarks>
        Private Overloads Shared Function UnmanagedBufferToByteArray(ByRef value As IntPtr, ByVal Length As UInteger) As Byte()
            Return UnmanagedBufferToByteArray(value, Length, True)
        End Function

        ''' <summary>
        ''' アンマネージドバッファをバイト列に変換します。
        ''' </summary>
        ''' <param name="value">変換対象のアンマネージドバッファのポインタを指定します。</param>
        ''' <param name="Length">変換対象のアンマネージドバッファの長さを指定します。</param>
        ''' <param name="Deallocate">変換対象のアンマネージドバッファを開放する場合はTrueを、それ以外の場合はFalseを指定します。</param>
        ''' <returns>変換によって生成されたバイト列を返します。</returns>
        ''' <remarks>DeallocateにTrueが指定された場合、valueに指定されたアンマネージドバッファは解放され、valueにはIntPtr.Zeroが代入されます。</remarks>
        Private Overloads Shared Function UnmanagedBufferToByteArray(ByRef value As IntPtr, ByVal Length As UInteger, ByVal Deallocate As Boolean) As Byte()
            If (value = IntPtr.Zero) Then
                Return Nothing
            End If
            Dim ByteArray As Byte() = New Byte(CInt(Length) - 1) {}
            RtlMoveMemory(ByteArray, value, Length)
            If (Deallocate) Then
                Marshal.FreeHGlobal(value)
                value = IntPtr.Zero
            End If
            Return ByteArray
        End Function
#End Region

#Region "外部変数宣言"
        ''' <summary>送信フラグ 変数宣言 As Short</summary>
        Private SendFlag As Short
        ''' <summary>Timer Box 変数宣言 As Single</summary>
        Private PauseTimems As Single
        ''' <summary>INI File Neme 定義 As String</summary>
        Private Shared INIFName As String = String.Empty
        ''' <summary>DLL Majorバージョン 変数宣言 As String</summary>
        Private Shared DLLMajor As String = String.Empty
        ''' <summary>LoadFlag 変数宣言 As Boolean</summary>
        Private LoadFlag As Boolean

        ' 開いたポート番号を追加
        Private portflag As Boolean() = New Boolean(255) {}
        ' 開いたポート番号の数
        Private portcount As Integer = 0

#End Region

#Region "ワーカスレッド定義"
        Private myWorker1 As Worker = New Worker("Worker1") ' ワーカスレッド1
        Private myWorker2 As Worker = New Worker("Worker2") ' ワーカスレッド2
        Private myWorker3 As Worker = New Worker("Worker3") ' ワーカスレッド3
#End Region

#Region "INIファイル操作"
        '指定のINIファイルから文字列を取得する(P989)
        <DllImport("KERNEL32.DLL", CharSet:=CharSet.Auto)> _
        Private Shared Function GetPrivateProfileString( _
                                           ByVal lpAppName As String, _
                                           ByVal lpKeyName As String, _
                                           ByVal lpDefault As String, _
                                           ByVal lpReturnedString As System.Text.StringBuilder, _
                                           ByVal nSize As Integer, _
                                           ByVal lpFileName As String) As Integer
        End Function
        '指定のINIファイルの指定のキーの文字列を変更する(P994)
        <DllImport("KERNEL32.DLL")> _
        Private Shared Function WritePrivateProfileString( _
                                           ByVal lpAppName As String, _
                                           ByVal lpKeyName As String, _
                                           ByVal lpString As String, _
                                           ByVal lpFileName As String) As Integer
        End Function
        '指定のINIファイルから整数値を取得する(P986)
        <DllImport("KERNEL32.DLL", CharSet:=CharSet.Auto)> _
        Private Shared Function GetPrivateProfileInt( _
                                           ByVal lpAppName As String, _
                                           ByVal lpKeyName As String, _
                                           ByVal nDefault As Integer, _
                                           ByVal lpFileName As String) As Integer
        End Function
        ''' <summary>
        ''' INI Fileから文字列型を取得します。
        ''' </summary>
        Private Shared Function ReadINI(ByVal Section As String, ByVal Entry As String, ByVal FileID As String) As String
            'INI ファイルから読み込み
            '戻り値(文字列)を受け取るバッファを準備
            Dim strBuffer As New System.Text.StringBuilder
            strBuffer.Capacity = 256   'バッファのサイズを指定
            Dim ret As Integer
            '文字列の値を取得する場合
            ret = GetPrivateProfileString(Section, Entry, "", strBuffer, strBuffer.Capacity, FileID)
            ReadINI = strBuffer.ToString

            '結果を表示
            Debug.WriteLine(ReadINI)
        End Function
        ''' <summary>
        ''' INI Fileに文字列を書き込みますします。
        ''' </summary>
        Private Shared Sub WriteINI(ByVal Section As String, ByVal Entry As String, ByVal EntryData As String, ByVal fileID As String)
            'INI ファイルに各キーに対する値を取得して書き込み
            Dim ret As Integer
            '書き込みは文字列も整数値(文字列に変換して)も同じ方法で
            ret = WritePrivateProfileString(Section, Entry, EntryData, fileID)

        End Sub
        ''' <summary>
        ''' INI を作成します。
        ''' </summary>
        Private Shared Sub CreateINI()
            Dim strLog As String = String.Empty

            If DLLMajor = "2" Then        'PCardRW64.DLL File Version 2.x.x.x 〜
                strLog = "-1"
            ElseIf DLLMajor = "1" Then    'PCardRW64.DLL File Version 1.x.x.x 〜
                strLog = "0"
            End If

            'Application　Name
            WriteINI("Application", "Name", "PCardRW64DLL INI File", INIFName)

            'LOG Configuration
            WriteINI("Log", "Logging", strLog, INIFName)
            WriteINI("Log", "LogFileName", ".\\PCardRW64_%03d.log", INIFName)

            'Send Delay Time Configuration
            WriteINI("Delay", "Delay", "0", INIFName)

            'WriteFile API TimeOut Configuration
            WriteINI("TimeOut", "WriteFileTimeOut", "5000", INIFName)
        End Sub
#End Region

#Region "(1) シリアルポート名取得処理 crwGetPortNames()"

        Private Sub GetPortNames_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles GetPortNames.Click
            Dim bpPortNames As IntPtr
            Dim piNumOfPort As Short

            'BSTR初期化
            Dim strPortNamesBSTR As System.IntPtr = ConvertStringToAnsiBSTR(String.Empty)

            '処理結果メッセージ初期化処理
            Call RetMsgInitialize()

            '初期化
            SendFlag = 0

            PortNames.Text = ""
            NumOfPort.Text = ""
            ' 初期化の方法はこれでいい？
            bpPortNames = 0

            '「crwGetPortNames」ボタン無効
            GetPortNames.Enabled = False
            'シリアルポート名取得
            'ret = crwGetPortNames(strPortNamesBSTR, iNumOfPort)
            Me.CallCrwFunction( _
                    New CrwGetPortNamesFunction( _
                                     bpPortNames, piNumOfPort, AddressOf crwGetPortNamesResultInvoker _
                    ) _
            )

            '「crwGetPortNames」ボタン有効
            GetPortNames.Enabled = True
            GetPortNames.Select()

        End Sub

        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwGetPortNamesResultHandler(ByVal ret As Boolean, ByVal bpPortNames As IntPtr, ByVal piNumOfPort As Short)

        ' 結果表示関数
        Sub crwGetPortNamesResult(ByVal ret As Boolean, ByVal bpPortNames As IntPtr, ByVal piNumOfPort As Short)

            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & GetPortNames.Text & Chr(&H22S)

            If (ret = True) Then

                PortNames.Text = ConvertAnsiBSTRToString(bpPortNames)                   ' ｼﾘｱﾙﾎﾟｰﾄ名設定
                DeleteAnsiBSTR(bpPortNames)
                ToolTip1.SetToolTip(PortNames, ConvertAnsiBSTRToString(bpPortNames))    ' ヒント表示
                NumOfPort.Text = piNumOfPort.ToString()                                 'ｼﾘｱﾙﾎﾟｰﾄ数設定

                RetVal.Text = "TRUE"
            Else
                RetVal.Text = "FALSE"
            End If

            Marshal.FreeBSTR(bpPortNames)  ' BSTR開放
        End Sub

        ' 結果表示関数呼出し
        Sub crwGetPortNamesResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwGetPortNamesFunction = CType(crwFunction, CrwGetPortNamesFunction)
            Me.BeginInvoke(New CrwGetPortNamesResultHandler(AddressOf crwGetPortNamesResult), New Object() {f._ret, f._bpPortNames, f._piNumOfPort})
        End Sub


#End Region

#Region "(2) COMポート情報取得関数 crwGetComDevInfo()"
        Private Sub GetComDevInfo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GetComDevInfo.Click

            Dim iPort As Short

            'BSTR初期化
            Dim bpDriveDescBSTR As IntPtr = ConvertStringToAnsiBSTR(String.Empty)
            Dim bpProviderNameBSTR As IntPtr = ConvertStringToAnsiBSTR(String.Empty)
            Dim bpDriveDateBSTR As IntPtr = ConvertStringToAnsiBSTR(String.Empty)
            Dim bpDriveVersionBSTR As IntPtr = ConvertStringToAnsiBSTR(String.Empty)

            '処理結果メッセージ初期化処理
            Call RetMsgInitialize()

            'COMポート
            iPort = CShort(Val(opPortNo.Text))

            '「crwGetComDevInfo」ボタン無効
            GetComDevInfo.Enabled = False

            'シリアルポート名取得
            'ret = crwGetComDevInfo(iPort, bpDriveDescBSTR, bpProviderNameBSTR, bpDriveDateBSTR, bpDriveVersionBSTR)
            Me.CallCrwFunction( _
                    New CrwGetComDevInfoFunction( _
                                     iPort, _
                                     bpDriveDescBSTR, _
                                     bpProviderNameBSTR, _
                                     bpDriveDateBSTR, _
                                     bpDriveVersionBSTR, _
                                     AddressOf crwGetComDevInfoResultInvoker _
                    ) _
            )
            '「crwGetComDevInfo」ボタン有効
            GetComDevInfo.Enabled = True
            GetComDevInfo.Select()

        End Sub
        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwGetComDevInfoResultHandler( _
                    ByVal ret As Boolean, _
                    ByRef bpDriverDescBSTR As IntPtr, _
                    ByRef bpProviderNameBSTR As IntPtr, _
                    ByRef bpDriverDateBSTR As IntPtr, _
                    ByRef bpDriverVersionBSTR As IntPtr)

        ' 結果表示関数
        Sub crwGetComDevInfoResult( _
                    ByVal ret As Boolean, _
                    ByRef bpDriverDescBSTR As IntPtr, _
                    ByRef bpProviderNameBSTR As IntPtr, _
                    ByRef bpDriverDateBSTR As IntPtr, _
                    ByRef bpDriverVersionBSTR As IntPtr)

            Dim iPort As Short
            Dim bpDriverDesc As String
            Dim bpProviderName As String
            Dim bpDriverDate As String
            Dim bpDriverVersion As String

            'COMポート
            iPort = CShort(Val(opPortNo.Text))

            ' BSTR -> Stringへの変換
            bpDriverDesc = ConvertAnsiBSTRToString(bpDriverDescBSTR)
            DeleteAnsiBSTR(bpDriverDescBSTR)
            bpProviderName = ConvertAnsiBSTRToString(bpProviderNameBSTR)
            DeleteAnsiBSTR(bpProviderNameBSTR)
            bpDriverDate = ConvertAnsiBSTRToString(bpDriverDateBSTR)
            DeleteAnsiBSTR(bpDriverDateBSTR)
            bpDriverVersion = ConvertAnsiBSTRToString(bpDriverVersionBSTR)
            DeleteAnsiBSTR(bpDriverVersionBSTR)

            '関数実行結果を表示
            If bpDriverDesc <> "" Then
                LbComDevInfo_0.Text = "Desc    :" & bpDriverDesc & "(COM" & CStr(iPort) & ")"
                ToolTip1.SetToolTip(LbComDevInfo_0, bpDriverDesc & "(COM" & CStr(iPort) & ")")
                LbComDevInfo_1.Text = "Provider:" & bpProviderName
                ToolTip1.SetToolTip(LbComDevInfo_1, bpProviderName)
                LbComDevInfo_2.Text = "Date    :" & bpDriverDate
                ToolTip1.SetToolTip(LbComDevInfo_2, bpDriverDate)
                LbComDevInfo_3.Text = "Version :" & bpDriverVersion
                ToolTip1.SetToolTip(LbComDevInfo_3, bpDriverVersion)
            End If

            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & GetComDevInfo.Text & Chr(&H22S)
            If (ret = True) Then
                RetVal.Text = "TRUE"
            Else
                RetVal.Text = "FALSE"
            End If

            ' BSTR開放
            Marshal.FreeBSTR(bpDriverDescBSTR)
            Marshal.FreeBSTR(bpProviderNameBSTR)
            Marshal.FreeBSTR(bpDriverDateBSTR)
            Marshal.FreeBSTR(bpDriverVersionBSTR)

        End Sub

        ' 結果表示関数呼出し
        Sub crwGetComDevInfoResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwGetComDevInfoFunction = CType(crwFunction, CrwGetComDevInfoFunction)
            Me.BeginInvoke(New CrwGetComDevInfoResultHandler(AddressOf crwGetComDevInfoResult), _
                           New Object() { _
                           f._ret, _
                           f._bpDriveDesc, _
                           f._bpProviderName, _
                           f._bpDriverDate, _
                           f._bpDriverVersion})
        End Sub
#End Region

#Region "(3) ポートオープン関数 crwOpenPort()"
        Private Sub OpenPort_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles OpenPort.Click

            Dim iPortNo As Short
            Dim lBaudRate As Integer
            Dim strDataBit As String
            Dim strParity As String

            'COMドライバー情報取得関数(crwGetComDevInfo)実行
            GetComDevInfo_Click(GetComDevInfo, New System.EventArgs())

            '処理結果メッセージ初期化処理
            Call RetMsgInitialize()

            'ポート番号、通信速度、データ長、パリティの設定
            iPortNo = CShort(Val(opPortNo.Text))
            lBaudRate = CInt(Val(opBaudRate.Text))
            strDataBit = opDataBit.Text
            strParity = VB.Left(opParity.Text, 1)
            ' ボタンを無効
            OpenPort.Enabled = False


            ' ポートオープン関数
            'ret = crwOpenPort(iPortNo, lBaudRate, strDataBit, strParity)
            Me.CallCrwFunction( _
                    New CrwOpenPortFunction( _
                            iPortNo, lBaudRate, strDataBit, strParity, _
                            AddressOf crwOpenPortResultInvoker _
                    ) _
            )


            ' ボタンを有効
            OpenPort.Enabled = True
            OpenPort.Select()

        End Sub
        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwOpenPortResultHandler(ByVal ret As Short, ByVal iPortNo As Short)
        'crwOpenPortResultInvoker
        '                            iPortNo, lBaudRate, strDataBit, strParity, _
        ' 結果表示関数
        Sub crwOpenPortResult(ByVal ret As Short, ByVal iPortNo As Short)

            Dim i As Short
            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & OpenPort.Text & Chr(&H22S)


            ' 正常Openの場合
            If ret = RET_CRW_SUCCESS Then
                ' 本プログラム内の他のポート番号を揃える
                For i = 0 To cpPortNo.Items.Count
                    If Val(VB6.GetItemString(cpPortNo, i)) = CDbl(opPortNo.Text) Then
                        cpPortNo.SelectedIndex = i
                        Exit For
                    End If
                Next i
                For i = 0 To scrPortNo.Items.Count
                    If Val(VB6.GetItemString(scrPortNo, i)) = CDbl(opPortNo.Text) Then
                        scrPortNo.SelectedIndex = i
                        Exit For
                    End If
                Next i
                For i = 0 To scPortNo.Items.Count
                    If Val(VB6.GetItemString(scPortNo, i)) = CDbl(opPortNo.Text) Then
                        scPortNo.SelectedIndex = i
                        Exit For
                    End If
                Next i
                For i = 0 To rrPortNo.Items.Count
                    If Val(VB6.GetItemString(rrPortNo, i)) = CDbl(opPortNo.Text) Then
                        rrPortNo.SelectedIndex = i
                        Exit For
                    End If
                Next i
                For i = 0 To sdPortNo.Items.Count
                    If Val(VB6.GetItemString(sdPortNo, i)) = CDbl(opPortNo.Text) Then
                        sdPortNo.SelectedIndex = i
                        Exit For
                    End If
                Next i
                For i = 0 To rdPortNo.Items.Count
                    If Val(VB6.GetItemString(rdPortNo, i)) = CDbl(opPortNo.Text) Then
                        rdPortNo.SelectedIndex = i
                        Exit For
                    End If
                Next i
                For i = 0 To sbdqPortNo.Items.Count
                    If Val(VB6.GetItemString(sbdqPortNo, i)) = CDbl(opPortNo.Text) Then
                        sbdqPortNo.SelectedIndex = i
                        Exit For
                    End If
                Next i
                For i = 0 To rbdPortNo.Items.Count
                    If Val(VB6.GetItemString(rbdPortNo, i)) = CDbl(opPortNo.Text) Then
                        rbdPortNo.SelectedIndex = i
                        Exit For
                    End If
                Next i
                For i = 0 To repPortNo.Items.Count
                    If Val(VB6.GetItemString(repPortNo, i)) = CDbl(opPortNo.Text) Then
                        repPortNo.SelectedIndex = i
                        Exit For
                    End If
                Next i
                For i = 0 To cepPortNo.Items.Count
                    If Val(VB6.GetItemString(cepPortNo, i)) = CDbl(opPortNo.Text) Then
                        cepPortNo.SelectedIndex = i
                        Exit For
                    End If
                Next i
                For i = 0 To sdrrPortNo.Items.Count
                    If Val(VB6.GetItemString(sdrrPortNo, i)) = CDbl(opPortNo.Text) Then
                        sdrrPortNo.SelectedIndex = i
                        Exit For
                    End If
                Next i
                For i = 0 To sdbccPortNo.Items.Count
                    If Val(VB6.GetItemString(sdbccPortNo, i)) = CDbl(opPortNo.Text) Then
                        sdbccPortNo.SelectedIndex = i
                        Exit For
                    End If
                Next i
                For i = 0 To rdbccPortNo.Items.Count
                    If Val(VB6.GetItemString(rdbccPortNo, i)) = CDbl(opPortNo.Text) Then
                        rdbccPortNo.SelectedIndex = i
                        Exit For
                    End If
                Next i
                For i = 0 To bccPortNo.Items.Count
                    If Val(VB6.GetItemString(bccPortNo, i)) = CDbl(opPortNo.Text) Then
                        bccPortNo.SelectedIndex = i
                        Exit For
                    End If
                Next i
                For i = 0 To crxbcPortNo.Items.Count
                    If Val(VB6.GetItemString(crxbcPortNo, i)) = CDbl(opPortNo.Text) Then
                        crxbcPortNo.SelectedIndex = i
                        Exit For
                    End If
                Next i
                For i = 0 To ibbsPortNo.Items.Count
                    If Val(VB6.GetItemString(ibbsPortNo, i)) = CDbl(opPortNo.Text) Then
                        ibbsPortNo.SelectedIndex = i
                        Exit For
                    End If
                Next i
                For i = 0 To pidsPortNo.Items.Count
                    If Val(VB6.GetItemString(pidsPortNo, i)) = CDbl(opPortNo.Text) Then
                        pidsPortNo.SelectedIndex = i
                        Exit For
                    End If
                Next i
                ' 開いたポート番号を登録する
                portflag(iPortNo - 1) = True
                ' 開いているポート番号の合計値をインクリメント
                portcount += 1

            End If

            RetVal.Text = ret.ToString()

        End Sub

        ' 結果表示関数呼出し
        Sub crwOpenPortResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwOpenPortFunction = CType(crwFunction, CrwOpenPortFunction)
            Me.BeginInvoke(New CrwOpenPortResultHandler(AddressOf crwOpenPortResult), New Object() {f._ret, f._iPortNo})

        End Sub
#End Region

#Region "(4) ポートクローズ処理 crwClosePort()"
        Private Sub ClosePort_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles ClosePort.Click

            Dim iPortNo As Short
            Call RetMsgInitialize()

            ' ポート番号設定
            iPortNo = CShort(Val(cpPortNo.Text))

            '処理結果メッセージ初期化処理
            Call RetMsgInitialize()

            ClosePort.Enabled = False

            ' ポートクローズ関数
            'ret = crwClosePort(iPortNo)
            Me.CallCrwFunction( _
                    New CrwClosePortFunction( _
                            iPortNo, _
                            AddressOf crwClosePortResultInvoker _
                    ) _
            )

            ClosePort.Enabled = True
            ClosePort.Select()

        End Sub
        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwClosePortResultHandler(ByVal ret As Short, ByVal iPortNo As Short)

        ' 結果表示関数
        Sub crwClosePortResult(ByVal ret As Short, ByVal iPortNo As Short)

            If ret = 0 Then

                ' ポート番号を未登録にする
                portflag(iPortNo - 1) = False
                ' 開いているポート番号の合計値をデクリメント
                portcount -= 1
            End If

            'LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & ClosePort.Text & Chr(&H22S)
            DisplayResult(ret, ClosePort.Text)
        End Sub

        ' 結果表示関数呼出し
        Sub crwClosePortResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwClosePortFunction = CType(crwFunction, CrwClosePortFunction)
            Me.BeginInvoke(New CrwClosePortResultHandler(AddressOf crwClosePortResult), New Object() {f._ret, f._iPortNo})
        End Sub
#End Region

#Region "(5) コマンド送受信関数 crwSendCommandRR()"
        Private Sub SendCommandRR_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles SendCommandRR.Click
            Dim iPortNo As Short
            Dim iRecMode As Short
            Dim lTimeOut As Integer
            Dim lBusyTimeOut As Integer
            Dim iDSRCheck As Short
            Dim lpCmdCode As String
            Dim lpCmdParam As String
            Dim iParamLen As Short
            Dim COMSTS As String
            Dim ERRSEN As String
            Dim ResData As String


            'BSTR初期化
            Dim ComStsBSTR As IntPtr = ConvertStringToAnsiBSTR(String.Empty)
            Dim ErrSenBSTR As IntPtr = ConvertStringToAnsiBSTR(String.Empty)
            Dim ResDataBSTR As IntPtr = ConvertStringToAnsiBSTR(String.Empty)

            SendFlag = 0

            ' 関数パラメータ初期化
            scrCOMSTS.Text = ""
            scrERRSEN.Text = ""
            scrResDATA.Text = ""
            COMSTS = ""
            ERRSEN = ""
            ResData = ""

            ' 処理結果初期化
            RetMsgInitialize()


            ' 関数パラメータ設定
            iPortNo = CShort(Val(scrPortNo.Text))
            iRecMode = CShort(Val(scrRecMode.Text))
            lTimeOut = Integer.Parse(scrTimeOut.Text)
            lBusyTimeOut = Integer.Parse(scrBusyTimeOut.Text)
            iDSRCheck = CShort(Val(scrDSRCheck.Text))
            lpCmdCode = scrCmdCode.Text
            lpCmdParam = scrCmdParam.Text
            iParamLen = CShort(Val(scrParamLen.Text))

            SendCommandRR.Enabled = False

            ' コマンド送受信関数実行
            'ret = crwSendCommandRR(iPortNo, iRecMode, lTimeOut, lBusyTimeOut, iDSRCheck, lpCmdCode, lpCmdParam, iParamLen, ComStsBSTR, ErrSenBSTR, ResDataBSTR)
            Me.CallCrwFunction( _
                    New CrwSendCommandRRFunction( _
                            iPortNo, _
                            iRecMode, _
                            lTimeOut, _
                            lBusyTimeOut, _
                            iDSRCheck, _
                            lpCmdCode, _
                            lpCmdParam, _
                            iParamLen, _
                            ComStsBSTR, _
                            ErrSenBSTR, _
                            ResDataBSTR, _
                            AddressOf crwSendCommandRRResultInvoker _
                    ) _
            )
            ' フォーカスを戻す
            SendCommandRR.Select()
            SendCommandRR.Enabled = True
            ' フォーカスを戻す
            SendCommandRR.Select()
        End Sub

        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwSendCommandRRResultHandler(ByVal ret As Short, _
                                                   ByVal bpCOMSTS As IntPtr, _
                                                   ByVal bpERRSEN As IntPtr, _
                                                   ByVal bpResDATA As IntPtr)

        ' 結果表示関数
        Sub crwSendCommandRRResult(ByVal ret As Short, _
                                   ByVal bpCOMSTS As IntPtr, _
                                   ByVal bpERRSEN As IntPtr, _
                                   ByVal bpResDATA As IntPtr)


            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & SendCommandRR.Text & Chr(&H22S)
            If ret = 0 Then    ' 結果が正常な場合
                ' 実行結果の表示
                scrCOMSTS.Text = ConvertAnsiBSTRToString(bpCOMSTS)
                DeleteAnsiBSTR(bpCOMSTS)
                scrERRSEN.Text = ConvertAnsiBSTRToString(bpERRSEN)
                DeleteAnsiBSTR(bpERRSEN)
                scrResDATA.Text = ConvertAnsiBSTRToString(bpResDATA)
                DeleteAnsiBSTR(bpResDATA)

                'ヒント設定
                ToolTip1.SetToolTip(scrResDATA, scrResDATA.Text)
            End If
            RetVal.Text = ret.ToString()

            ' BSTR開放
            Marshal.FreeBSTR(bpCOMSTS)
            Marshal.FreeBSTR(bpERRSEN)
            Marshal.FreeBSTR(bpResDATA)

            ' 関数処理結果表示
            DisplayResult(ret, SendCommandRR.Text)

            ' フォーカスを戻す
            SendCommandRR.Select()
        End Sub

        ' 結果表示関数呼出し
        Sub crwSendCommandRRResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwSendCommandRRFunction = CType(crwFunction, CrwSendCommandRRFunction)
            Me.BeginInvoke(New CrwSendCommandRRResultHandler(AddressOf crwSendCommandRRResult), _
                           New Object() { _
                                        f._ret, _
                                        f._bpCOMSTS, _
                                        f._bpERRSEN, _
                                        f._bpResDATA})
        End Sub
#End Region

#Region "(6) コマンド送信関数 crwSendCommand()"
        Private Sub SendCommand_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles SendCommand.Click

            Dim iPortNo As Short
            Dim lTimeOut As Integer
            Dim iDSRCheck As Short
            Dim lpCmdCode As String
            Dim lpCmdParam As String
            Dim iParamLen As Short

            SendFlag = 1

            ' 処理結果メッセージ初期化処理
            Call RetMsgInitialize()

            ' 関数パラメータ設定
            iPortNo = CShort(Val(scPortNo.Text))
            lTimeOut = Integer.Parse(scTimeOut.Text)
            iDSRCheck = CShort(Val(scDSRCheck.Text))
            lpCmdCode = scCmdCode.Text
            lpCmdParam = scCmdParam.Text
            iParamLen = CShort(Val(scParamLen.Text))

            '「crwSendCommand」ボタン無効
            SendCommand.Enabled = False

            ' コマンド送信関数実行
            'ret = crwSendCommand(iPortNo, lTimeOut, iDSRCheck, lpCmdCode, lpCmdParam, iParamLen)
            Me.CallCrwFunction( _
                    New CrwSendCommandFunction( _
                            iPortNo, _
                            lTimeOut, _
                            iDSRCheck, _
                            lpCmdCode, _
                            lpCmdParam, _
                            iParamLen, _
                            AddressOf crwSendCommandResultInvoker _
                    ) _
            )
            '「crwSendCommand」ボタン有効
            SendCommand.Enabled = True
            SendCommand.Select()

        End Sub

        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwSendCommandResultHandler(ByVal ret As Short)

        ' 結果表示関数
        Sub crwSendCommandResult(ByVal ret As Short)

            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & SendCommand.Text & Chr(&H22S)
            If ret = 0 Then    ' 結果が正常な場合
                ' 実行結果の表示

                ToolTip1.SetToolTip(scrResDATA, scrResDATA.Text)
            End If

            RetVal.Text = ret.ToString()

            ' 処理結果表示
            DisplayResult(ret, SendCommand.Text)

            If ret = RET_CRW_SUCCESS Then
                If _OpSendCommand_1.Checked = True Then
                    'レスポンス受信関数(ReceiveResponse)実行
                    ReceiveResponse_Click(ReceiveResponse, New System.EventArgs())
                ElseIf _OpSendCommand_2.Checked = True Then
                    SSTab1.SelectedIndex = 4
                    ' 全イベントチェックボックス"TRUE"
                    repRecMode.Text = "1"                                               'iRecMode
                    repCheckAll.CheckState = System.Windows.Forms.CheckState.Unchecked  'All Events
                    _repCheck_0.CheckState = System.Windows.Forms.CheckState.Checked    'EVT_RSP_CRW_RESPONSE
                    _repCheck_1.CheckState = System.Windows.Forms.CheckState.Unchecked  'EVT_RSP_CRW_READY
                    _repCheck_2.CheckState = System.Windows.Forms.CheckState.Unchecked  'EVT_RSP_CRW_BUSY
                    _repCheck_3.CheckState = System.Windows.Forms.CheckState.Checked    'EVT_RSP_CRW_ERR_RES_TIMEOUT
                    _repCheck_4.CheckState = System.Windows.Forms.CheckState.Checked    'EVT_RSP_CRW_ERR_CTS_TIMEOUT
                    _repCheck_5.CheckState = System.Windows.Forms.CheckState.Checked    'EVT_RSP_CRW_ERR_DSR
                    _repCheck_6.CheckState = System.Windows.Forms.CheckState.Checked    'EVT_RSP_CRW_ERR_BCC_RETRY
                    _repCheck_7.CheckState = System.Windows.Forms.CheckState.Checked    'EVT_RSP_CRW_ERR_COMM_WRITE
                    _repCheck_8.CheckState = System.Windows.Forms.CheckState.Checked    'EVT_RSP_CRW_ERR_COMM_READ
                    _repCheck_9.CheckState = System.Windows.Forms.CheckState.Checked    'EVT_RSP_CRW_CANCELED
                    'レスポンス受信イベントハンドラ登録関数実行(SetResponseEventProc)
                    SetResponseEventProc_Click(SetResponseEventProc, New System.EventArgs())
                End If
            End If


        End Sub

        ' 結果表示関数呼出し
        Sub crwSendCommandResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwSendCommandFunction = CType(crwFunction, CrwSendCommandFunction)
            Me.BeginInvoke(New CrwSendCommandResultHandler(AddressOf crwSendCommandResult), _
                           New Object() {f._ret})
        End Sub

#End Region

#Region "(7) レスポンス受信関数 crwReceiveResponse()"
        Private Sub ReceiveResponse_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles ReceiveResponse.Click

            Dim iPortNo As Short
            Dim iRecMode As Short
            Dim lTimeOut As Integer
            Dim iDSRCheck As Short


            'BSTR初期化
            Dim ComStsBSTR As IntPtr = ConvertStringToAnsiBSTR(String.Empty)
            Dim ErrSenBSTR As IntPtr = ConvertStringToAnsiBSTR(String.Empty)
            Dim ResDataBSTR As IntPtr = ConvertStringToAnsiBSTR(String.Empty)

            SendFlag = 0

            ' TextBox初期化
            rrCOMSTS.Text = ""
            rrERRSEN.Text = ""
            rrResDATA.Text = ""

            ' 処理結果初期化
            Call RetMsgInitialize()

            ' 関数パラメータ設定
            iPortNo = CShort(Val(rrPortNo.Text))
            iRecMode = CShort(Val(rrRecMode.Text))
            lTimeOut = Integer.Parse(rrTimeOut.Text)
            iDSRCheck = CShort(Val(rrDSRCheck.Text))

            ReceiveResponse.Enabled = False

            ' レスポンス受信関数実行
            'ret = crwReceiveResponse(iPortNo, iRecMode, lTimeOut, iDSRCheck, ComStsBSTR, ErrSenBSTR, ResDataBSTR)
            Me.CallCrwFunction( _
                    New CrwReceiveResponseFunction( _
                            iPortNo, _
                            iRecMode, _
                            lTimeOut, _
                            iDSRCheck, _
                            ComStsBSTR, _
                            ErrSenBSTR, _
                            ResDataBSTR, _
                            AddressOf crwReceiveResponseResultInvoker _
                    ) _
            )
            ReceiveResponse.Enabled = True
            ReceiveResponse.Select()

        End Sub

        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwReceiveResponseResultHandler(ByVal ret As Short, _
                                                     ByVal bpCOMSTS As IntPtr, _
                                                     ByVal bpERRSEN As IntPtr, _
                                                     ByVal bpResDATA As IntPtr)
        ' 結果表示関数
        Sub crwReceiveResponseResult(ByVal ret As Short, _
                                     ByVal bpCOMSTS As IntPtr, _
                                     ByVal bpERRSEN As IntPtr, _
                                     ByVal bpResDATA As IntPtr)

            Dim COMSTS As String
            Dim ERRSEN As String
            Dim ResData As String
            ' 文字列変数初期化
            COMSTS = ""
            ERRSEN = ""
            ResData = ""

            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & ReceiveResponse.Text & Chr(&H22S)

            'BSTR -> Stringへの変換
            COMSTS = ConvertAnsiBSTRToString(bpCOMSTS)
            DeleteAnsiBSTR(bpCOMSTS)
            ERRSEN = ConvertAnsiBSTRToString(bpERRSEN)
            DeleteAnsiBSTR(bpERRSEN)
            ResData = ConvertAnsiBSTRToString(bpResDATA)
            DeleteAnsiBSTR(bpResDATA)

            ' 関数結果をFormのTextBoxへ反映
            rrCOMSTS.Text = COMSTS
            rrERRSEN.Text = ERRSEN
            rrResDATA.Text = ResData
            ToolTip1.SetToolTip(rrResDATA, ResData)

            ' BSTR開放
            Marshal.FreeBSTR(bpResDATA)
            Marshal.FreeBSTR(bpCOMSTS)
            Marshal.FreeBSTR(bpERRSEN)

            ' 処理結果表示(ボタンのテキストを指定)
            DisplayResult(ret, ReceiveResponse.Text)

        End Sub

        ' 結果表示関数呼出し
        Sub crwReceiveResponseResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwReceiveResponseFunction = CType(crwFunction, CrwReceiveResponseFunction)
            Me.BeginInvoke(New CrwReceiveResponseResultHandler(AddressOf crwReceiveResponseResult), _
                           New Object() {f._ret, _
                                         f._bpCOMSTS, _
                                         f._bpERRSEN, _
                                         f._bpResDATA})
        End Sub
#End Region

#Region "(8) データ送信関数(応答あり) crwSendDataWR()"
        Private Sub SendDataWR_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles SendDataWR.Click

            Dim iPortNo As Short
            Dim lTimeOut As Integer
            Dim iDSRCheck As Short
            Dim lpData As String
            Dim lpDataLen As Short
            Dim UnmanagedBuff As IntPtr
            Dim i As Short
            Dim Work1, Work2 As String

            SendFlag = 0

            ' 処理結果初期化
            Call RetMsgInitialize()

            ' 関数パラメータ設定
            iPortNo = CShort(Val(sdPortNo.Text))
            '            lTimeOut = CInt(Val(sdTimeOut.Text))
            lTimeOut = Integer.Parse(sdTimeOut.Text)
            iDSRCheck = CShort(Val(sdDSRCheck.Text))

            'バイナリ文字列から、Char変換
            If ChksdDataBin.Checked = True Then
                If Len(TxtSdDataBin.Text) Mod 2 <> 0 Then
                    MsgBox("データが偶数ではありません")
                    Exit Sub
                Else
                    i = 1 : Work2 = ""
                    For i = 1 To Len(TxtSdDataBin.Text) Step 2
                        Work1 = Mid(TxtSdDataBin.Text, i, 2)
                        Work2 = Work2 & Chr("&h" + Work1)
                    Next
                    sdData.Text = Work2
                End If
            End If
            lpData = sdData.Text
            lpDataLen = Val(sdDatalen.Text)

            'LPCSTR準備
            UnmanagedBuff = Marshal.StringToHGlobalAnsi(lpData)

            SendDataWR.Enabled = False

            ' データ送信関数(応答あり)実行
            'ret = crwSendDataWR(iPortNo, lTimeOut, iDSRCheck, UnmanagedBuff, lpDataLen)
            Me.CallCrwFunction( _
                    New CrwSendDataWRFunction( _
                            iPortNo, _
                            lTimeOut, _
                            iDSRCheck, _
                            UnmanagedBuff, _
                            lpDataLen, _
                            AddressOf crwSendDataWRResultInvoker _
                    ) _
            )

            SendDataWR.Enabled = True
            SendDataWR.Select()

            'LPCSTR後処理
            'Marshal.FreeHGlobal(UnmanagedBuff)

        End Sub

        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwSendDataWRResultHandler(ByVal ret As Short, ByVal UnmanagedBuff As IntPtr)

        ' 結果表示関数
        Sub crwSendDataWRResult(ByVal ret As Short, ByVal UnmanagedBuff As IntPtr)

            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & SendDataWR.Text & Chr(&H22S)

            ' 開放
            Marshal.FreeHGlobal(UnmanagedBuff)

            ' 処理結果表示
            DisplayResult(ret, SendDataWR.Text)

        End Sub

        ' 結果表示関数呼出し
        Sub crwSendDataWRResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwSendDataWRFunction = CType(crwFunction, CrwSendDataWRFunction)
            Me.BeginInvoke(New CrwSendDataWRResultHandler(AddressOf crwSendDataWRResult), _
                           New Object() {f._ret, f._lpData})
        End Sub
#End Region

#Region "(9) データ送信関数(応答なし) crwSendDataQR()"
        Private Sub SendDataQR_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles SendDataQR.Click

            Dim iPortNo As Short
            Dim lTimeOut As Integer
            Dim iDSRCheck As Short
            Dim lpData As String
            Dim lpDataLen As Short
            Dim UnmanagedBuff As IntPtr
            Dim i As Short
            Dim Work1, Work2 As String

            SendFlag = 0

            ' 処理結果初期化
            Call RetMsgInitialize()

            ' 関数パラメータ設定
            iPortNo = CShort(Val(sdPortNo.Text))
            '            lTimeOut = CInt(Val(sdTimeOut.Text))
            lTimeOut = Integer.Parse(sdTimeOut.Text)
            iDSRCheck = CShort(Val(sdDSRCheck.Text))
            'バイナリ文字列から、Char変換
            If ChksdDataBin.Checked = True Then
                If Len(TxtSdDataBin.Text) Mod 2 <> 0 Then
                    MsgBox("データが偶数ではありません")
                    Exit Sub
                Else
                    i = 1 : Work2 = ""
                    For i = 1 To Len(TxtSdDataBin.Text) Step 2
                        Work1 = Mid(TxtSdDataBin.Text, i, 2)
                        Work2 = Work2 & Chr("&h" + Work1)
                    Next
                    sdData.Text = Work2
                End If
            End If
            lpData = sdData.Text
            lpDataLen = Val(sdDatalen.Text)

            'LPCSTR準備
            UnmanagedBuff = Marshal.StringToHGlobalAnsi(lpData)

            SendDataQR.Enabled = False

            ' データ送信関数(応答なし)実行
            'ret = crwSendDataQR(iPortNo, lTimeOut, iDSRCheck, UnmanagedBuff, lpDataLen)
            Me.CallCrwFunction( _
                    New CrwSendDataQRFunction( _
                            iPortNo, _
                            lTimeOut, _
                            iDSRCheck, _
                            UnmanagedBuff, _
                            lpDataLen, _
                            AddressOf crwSendDataQRResultInvoker _
                    ) _
            )
            SendDataQR.Enabled = True
            SendDataQR.Select()

            'LPCSTR後処理
            'Marshal.FreeHGlobal(UnmanagedBuff)

        End Sub
        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwSendDataQRResultHandler(ByVal ret As Short, ByVal UnmanagedBuff As IntPtr)

        ' 結果表示関数
        Sub crwSendDataQRResult(ByVal ret As Short, ByVal UnmanagedBuff As IntPtr)

            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & SendDataQR.Text & Chr(&H22S)
            If ret = 0 Then    ' 結果が正常な場合
                ' 実行結果の表示

                ToolTip1.SetToolTip(scrResDATA, scrResDATA.Text)
            End If

            ' 開放はこれでよい？
            Marshal.FreeHGlobal(UnmanagedBuff)
            RetVal.Text = ret.ToString()

            ' 処理結果表示
            DisplayResult(ret, SendDataQR.Text)

            ' 正常処理の場合
            If ret = RET_CRW_SUCCESS Then
                If OpSendData(1).Checked = True Then
                    ReceiveData.Enabled = False
                    If Val(TxtTimeSendData.Text) <> 0 Then
                        PauseTimems = Val(TxtTimeSendData.Text) / 1000
                        Debug.Print("PauseTimems = " & PauseTimems & "s")
                        ' 処理一時停止
                        Pause(PauseTimems)
                    End If
                    ' データ受信関数実行
                    ReceiveData_Click(ReceiveData, New System.EventArgs())
                    ReceiveData.Enabled = True
                ElseIf OpSendData(2).Checked = True Then
                    SSTab1.SelectedIndex = 3
                    ReceiveBinaryData.Enabled = False
                    If Val(TxtTimeSendData.Text) <> 0 Then
                        PauseTimems = Val(TxtTimeSendData.Text) / 1000
                        Debug.Print("PauseTimems = " & PauseTimems & "s")
                        ' 処理一時停止
                        Pause(PauseTimems)
                    End If
                    ' バイナリデータ受信関数実行
                    ReceiveBinaryData_Click(ReceiveBinaryData, New System.EventArgs())
                    ReceiveBinaryData.Enabled = True
                End If
            End If

        End Sub

        ' 結果表示関数呼出し
        Sub crwSendDataQRResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwSendDataQRFunction = CType(crwFunction, CrwSendDataQRFunction)
            Me.BeginInvoke(New CrwSendDataQRResultHandler(AddressOf crwSendDataQRResult), _
                           New Object() {f._ret, f._lpData})
        End Sub
#End Region

#Region "(10) データ受信関数 crwReceiveData()"
        Public Sub ReceiveData_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles ReceiveData.Click

            Dim iPortNo As Short
            Dim iDSRCheck As Short
            Dim ResData As String
            Dim iDataLength As Short

            'BSTR初期化
            Dim bpResDATA As IntPtr = ConvertStringToAnsiBSTR(String.Empty)
            SendFlag = 0
            ResData = ""

            ' 文字列初期化
            rdResData.Text = ""
            rdDataLen.Text = ""
            TxtrdResDataBin.Text = ""

            ' 処理結果初期化
            Call RetMsgInitialize()

            ' 関数パラメータ設定
            iPortNo = CShort(Val(rdPortNo.Text))
            iDSRCheck = CShort(Val(rdDSRCheck.Text))

            ReceiveData.Enabled = False

            ' データ受信関数実行
            'ret = crwReceiveData(iPortNo, iDSRCheck, ResDataBSTR, DataLen)
            Me.CallCrwFunction( _
                    New CrwReceiveDataFunction( _
                            iPortNo, _
                            iDSRCheck, _
                            bpResDATA, _
                            iDataLength, _
                            AddressOf crwReceiveDataResultInvoker _
                    ) _
            )
            ReceiveData.Enabled = True
            ReceiveData.Select()
        End Sub

        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwReceiveDataResultHandler(ByVal ret As Short, _
                                                   ByRef bpResDATA As IntPtr, _
                                                   ByRef iDataLength As Short)

        ' 結果表示関数
        Sub crwReceiveDataResult(ByVal ret As Short, _
                                   ByRef bpResDATA As IntPtr, _
                                   ByRef iDataLength As Short)

            Dim i As Short
            Dim Work1 As String
            Dim Work2 As String
            Dim ResData As String


            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & ReceiveData.Text & Chr(&H22S)

            'BSTR -> String変換
            ResData = ConvertAnsiBSTRToString(bpResDATA)
            DeleteAnsiBSTR(bpResDATA)

            Marshal.FreeBSTR(bpResDATA)  ' BSTR開放

            ' FormのTextBoxへ実行結果を設定
            rdResData.Text = ResData
            ' ASCIIコード変換
            i = 1 : Work2 = ""
            For i = 1 To Len(ResData)
                Work1 = Asc(Mid(ResData, i, 1))
                Work2 = Work2 & Strings.Right("0" & CStr(Hex(Work1)), 2) & " "
            Next
            TxtrdResDataBin.Text = Work2

            ' ヒントメッセージ設定
            ToolTip1.SetToolTip(rdResData, ResData)
            rdDataLen.Text = CStr(iDataLength)

            ' 処理結果表示
            DisplayResult(ret, ReceiveData.Text)

        End Sub

        ' 結果表示関数呼出し
        Sub crwReceiveDataResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwReceiveDataFunction = CType(crwFunction, CrwReceiveDataFunction)
            Me.BeginInvoke(New CrwReceiveDataResultHandler(AddressOf crwReceiveDataResult), _
                           New Object() {f._ret, _
                                         f._bpResDATA, _
                                         f._iDataLength})
        End Sub
#End Region

#Region "(11) 電文データ送受信関数実行 crwSendDataRR()"
        Private Sub SendDataRR_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SendDataRR.Click
            Dim iPortNo As Short
            Dim iRetryCount As Short
            Dim lTimeOut As Integer
            Dim iDSRCheck As Short
            Dim lpData As String
            Dim iDataLength As Short
            Dim bpResDATA As String
            Dim piDataLength As Short
            Dim UnmanagedBuff As IntPtr

            'BSTR初期化
            Dim ResDataBSTR As IntPtr = ConvertStringToAnsiBSTR(String.Empty)

            '初期化
            SendFlag = 0

            sdrrResData.Text = ""
            sdrrResDataLen.Text = ""
            bpResDATA = ""

            '処理結果メッセージ表示
            Call RetMsgInitialize()

            '関数パラメータ設定
            iPortNo = CShort(Val(sdrrPortNo.Text))
            iRetryCount = CShort(Val(sdrrRetryCount.Text))
            '            lTimeOut = CInt(Val(sdbccTimeOut.Text))
            lTimeOut = Integer.Parse(sdbccTimeOut.Text)
            iDSRCheck = CShort(Val(sdrrDSRCheck.Text))
            lpData = sdrrSendData.Text
            iDataLength = CShort(Val(sdrrSendDataLen.Text))

            'LPCSTR準備
            UnmanagedBuff = Marshal.StringToHGlobalAnsi(lpData)

            '「crwSendDataRR」ボタン無効
            SendDataRR.Enabled = False

            '電文データ送受信関数実行
            'ret = crwSendDataRR(iPortNo, iRetryCount, lTimeOut, iDSRCheck, UnmanagedBuff, iDataLength, ResDataBSTR, piDataLength)
            Me.CallCrwFunction( _
                    New CrwSendDataRRFunction( _
                            iPortNo, _
                            iRetryCount, _
                            lTimeOut, _
                            iDSRCheck, _
                            UnmanagedBuff, _
                            iDataLength, _
                            ResDataBSTR, _
                            piDataLength, _
                            AddressOf crwSendDataRRResultInvoker _
                    ) _
            )


            '「crwSendDataRR」ボタン有効
            SendDataRR.Enabled = True
            SendDataRR.Select()

            'LPCSTR後処理
            'Marshal.FreeHGlobal(UnmanagedBuff)


        End Sub

        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwSendDataRRResultHandler(ByVal ret As Short, _
                                                   ByRef UnmanagedBuff As IntPtr, _
                                                   ByVal bpResDATA As IntPtr, _
                                                   ByVal piDataLength As Short)

        ' 結果表示関数
        Sub crwSendDataRRResult(ByVal ret As Short, _
                                   ByRef UnmanagedBuff As IntPtr, _
                                   ByVal bpResDATA As IntPtr, _
                                   ByVal piDataLength As Short)
            Dim ResData As String

            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & SendCommandRR.Text & Chr(&H22S)

            'BSTR -> Stringへの変換
            ResData = ConvertAnsiBSTRToString(bpResDATA)
            DeleteAnsiBSTR(bpResDATA)

            Marshal.FreeBSTR(bpResDATA)  ' BSTR開放

            '関数実行結果を表示
            sdrrResData.Text = ResData
            ToolTip1.SetToolTip(sdrrResData, ResData)
            sdrrResDataLen.Text = CStr(piDataLength)

            'LPCSTR後処理
            Marshal.FreeHGlobal(UnmanagedBuff)

            ' 処理結果表示
            DisplayResult(ret, SendDataRR.Text)

        End Sub

        ' 結果表示関数呼出し
        Sub crwSendDataRRResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwSendDataRRFunction = CType(crwFunction, CrwSendDataRRFunction)
            Me.BeginInvoke(New CrwSendDataRRResultHandler(AddressOf crwSendDataRRResult), _
                           New Object() {f._ret, _
                                         f._lpData, _
                                         f._bpResDATA, _
                                         f._piDataLength})
        End Sub

#End Region

#Region "(12) 電文データ送信関数 crwSendDataBCC()"
        Private Sub SendDataBCC_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SendDataBCC.Click
            Dim iPortNo As Short
            Dim iACKCount As Short
            Dim iRetryCount As Short
            Dim lTimeOut As Integer
            Dim iDSRCheck As Short
            Dim lpData As String
            Dim ipDataLength As Short
            Dim UnmanagedBuff As IntPtr

            SendFlag = 0

            '処理結果メッセージ初期化
            Call RetMsgInitialize()

            '関数パラメータ設定
            iPortNo = CShort(Val(sdbccPortNo.Text))
            iACKCount = CShort(Val(sdbccACKCount.Text))
            iRetryCount = CShort(Val(sdbccRetryCount.Text))
            lTimeOut = Integer.Parse(sdbccTimeOut.Text)
            iDSRCheck = CShort(Val(sdbccDSRCheck.Text))
            lpData = sdbccSendData.Text
            ipDataLength = CShort(Val(sdbccSendDataLen.Text))

            'LPCSTR準備
            UnmanagedBuff = Marshal.StringToHGlobalAnsi(lpData)

            '「crwSendDataBCC」ボタン無効
            SendDataBCC.Enabled = False

            '電文データ送信関数実行
            'ret = crwSendDataBCC(iPortNo, iACKCount, iRetryCount, lTimeOut, iDSRCheck, UnmanagedBuff, ipDataLength)
            Me.CallCrwFunction( _
                    New CrwSendDataBCCFunction( _
                            iPortNo, _
                            iACKCount, _
                            iRetryCount, _
                            lTimeOut, _
                            iDSRCheck, _
                            UnmanagedBuff, _
                            ipDataLength, _
                            AddressOf crwSendDataBCCResultInvoker _
                    ) _
            )

            '「crwSendDataBCC」ボタン有効
            SendDataBCC.Enabled = True

            'LPCSTR後処理
            Marshal.FreeHGlobal(UnmanagedBuff)

        End Sub

        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwSendDataBCCResultHandler(ByVal ret As Short, _
                                                   ByRef UnmanagedBuff As IntPtr, _
                                                   ByRef lpDataLength As Short)

        ' 結果表示関数
        Sub crwSendDataBCCResult(ByVal ret As Short, _
                                   ByRef UnmanagedBuff As IntPtr, _
                                   ByRef lpDataLength As Short)

            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & SendDataBCC.Text & Chr(&H22S)

            '処理結果表示
            DisplayResult(ret, SendDataBCC.Text)

            '処理が正常終了のい場合
            If ret = RET_CRW_SUCCESS Then
                '「crwReceiveDataBCC」選択の場合
                If _OpSendDataBCC_1.Checked = True Then
                    ReceiveDataBCC.Enabled = False
                    If Val(TxtTimeSendDataBCC.Text) <> 0 Then
                        PauseTimems = Val(TxtTimeSendDataBCC.Text) / 1000
                        Debug.Print("PauseTimems = " & PauseTimems & "s")
                        Pause(PauseTimems)
                    End If
                    'crwReceiveDataBCC実行関数呼出()
                    ReceiveDataBCC_Click(ReceiveDataBCC, New System.EventArgs())
                    ReceiveDataBCC.Enabled = True
                ElseIf _OpSendDataBCC_2.Checked Then
                    '「crwReceiveBinaryData」選択の場合
                    SSTab1.SelectedIndex = 3
                    ReceiveBinaryData.Enabled = False
                    If Val(TxtTimeSendData.Text) <> 0 Then
                        PauseTimems = Val(TxtTimeSendData.Text) / 1000
                        Debug.Print("PauseTimems = " & PauseTimems & "s")
                        ' 処理一時停止
                        Pause(PauseTimems)
                    End If
                    ' バイナリデータ受信関数実行
                    ReceiveBinaryData_Click(ReceiveBinaryData, New System.EventArgs())
                    ReceiveBinaryData.Enabled = True
                ElseIf _OpSendDataBCC_3.Checked = True Then
                    '「crwSetReceiveDataBCCEventProc」選択の場合
                    SSTab1.SelectedIndex = 4
                    SetReceiveDataBCCEventProc.Enabled = False
                    bccChkAll.CheckState = System.Windows.Forms.CheckState.Unchecked 'ALL Events = OFF
                    bccChk_0.CheckState = System.Windows.Forms.CheckState.Checked 'EVT_BCC_CRW_RESPONSE
                    bccChk_1.CheckState = System.Windows.Forms.CheckState.Checked 'EVT_BCC_CRW_ERR_RES_TIMEOUT
                    bccChk_2.CheckState = System.Windows.Forms.CheckState.Checked 'EVT_BCC_CRW_ERR_CTS_TIMEOUT
                    bccChk_3.CheckState = System.Windows.Forms.CheckState.Checked 'EVT_BCC_CRW_ERR_DSR
                    bccChk_4.CheckState = System.Windows.Forms.CheckState.Checked 'EVT_BCC_CRW_ERR_BCC_RETRY
                    bccChk_5.CheckState = System.Windows.Forms.CheckState.Checked 'EVT_BCC_CRW_ERR_COMM_WRITE
                    bccChk_6.CheckState = System.Windows.Forms.CheckState.Checked 'EVT_BCC_CRW_ERR_COMM_READ
                    bccChk_7.CheckState = System.Windows.Forms.CheckState.Checked 'EVT_BCC_CRW_CANCELED
                    bccEntry.Checked = True 'コールバック登録
                    'Wait Timer
                    If Val(TxtTimeSendDataBCC.Text) <> 0 Then
                        PauseTimems = Val(TxtTimeSendDataBCC.Text) / 1000
                        Debug.Print("PauseTimems = " & PauseTimems & "s")
                        Pause(PauseTimems)
                    End If
                    'crwSetCommEventProc実行関数呼出
                    SetReceiveDataBCCEventProc_Click(SetCommEventProc, New System.EventArgs())
                    SetReceiveDataBCCEventProc.Enabled = True
                ElseIf _OpSendDataBCC_4.Checked = True Then
                    '「crwSetCommEventProc」選択の場合
                    SSTab1.SelectedIndex = 4
                    SetCommEventProc.Enabled = False
                    cepCheckAll.CheckState = System.Windows.Forms.CheckState.Unchecked 'ALL Events = OFF
                    _cepCheck_0.CheckState = System.Windows.Forms.CheckState.Checked 'EVT_CRW_RXCHAR
                    _cepCheck_2.CheckState = System.Windows.Forms.CheckState.Checked 'EVT_CRW_ERR_FRAME
                    _cepCheck_3.CheckState = System.Windows.Forms.CheckState.Checked 'EVT_CRW_ERR_OVERRUN
                    _cepCheck_4.CheckState = System.Windows.Forms.CheckState.Checked 'EVT_CRW_ERR_PARITY
                    _cepCheck_6.CheckState = System.Windows.Forms.CheckState.Checked 'EVT_CRW_DSR
                    _cepCheck_8.CheckState = System.Windows.Forms.CheckState.Checked 'EVT_CRW_BREAK
                    cepEntry.Checked = True 'コールバック登録
                    'Wait Timer
                    If Val(TxtTimeSendDataBCC.Text) <> 0 Then
                        PauseTimems = Val(TxtTimeSendDataBCC.Text) / 1000
                        Debug.Print("PauseTimems = " & PauseTimems & "s")
                        Pause(PauseTimems)
                    End If
                    'crwSetCommEventProc実行関数呼出
                    SetCommEventProc_Click(SetCommEventProc, New System.EventArgs())
                    SetCommEventProc.Enabled = True
                End If
            End If
        End Sub

        ' 結果表示関数呼出し
        Sub crwSendDataBCCResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwSendDataBCCFunction = CType(crwFunction, CrwSendDataBCCFunction)
            Me.BeginInvoke(New CrwSendDataBCCResultHandler(AddressOf crwSendDataBCCResult), _
                           New Object() {f._ret, _
                                         f._lpData, _
                                         f._iDataLength})
        End Sub

#End Region

#Region "(13) 電文データ受信関数 crwReceiveDataBCC()"
        Private Sub ReceiveDataBCC_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReceiveDataBCC.Click
            Dim iPortNo As Short
            Dim iACKResponse As Short
            Dim lTimeOut As Integer
            Dim iDSRCheck As Short
            Dim bpResDATA As String
            Dim piDataLength As Short

            'BSTR初期化
            Dim ResDataBSTR As IntPtr = ConvertStringToAnsiBSTR(String.Empty)

            '初期化
            SendFlag = 0

            rdbccResData.Text = ""
            rdbccResDataLen.Text = ""
            bpResDATA = ""

            '処理結果メッセージ初期化
            Call RetMsgInitialize()

            '関数パラメータ設定
            iPortNo = CShort(Val(rdbccPortNo.Text))
            iACKResponse = CShort(Val(rdbccACKResponse.Text))
            lTimeOut = CInt(Val(rdbccTimeOut.Text))
            iDSRCheck = CShort(Val(rdbccDSRCheck.Text))

            '「crwReceiveDataBCC」ボタンを無効
            ReceiveDataBCC.Enabled = False

            '電文データ受信関数実行
            'ret = crwReceiveDataBCC(iPortNo, iACKResponse, lTimeOut, iDSRCheck, ResDataBSTR, piDataLength)
            Me.CallCrwFunction( _
                    New CrwReceiveDataBCCFunction( _
                            iPortNo, _
                            iACKResponse, _
                            lTimeOut, _
                            iDSRCheck, _
                            ResDataBSTR, _
                            piDataLength, _
                            AddressOf crwReceiveDataBCCResultInvoker _
                    ) _
            )
            ReceiveDataBCC.Enabled = True
            ReceiveDataBCC.Select()

        End Sub

        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwReceiveDataBCCResultHandler(ByVal ret As Short, _
                                                ByVal bpResData As IntPtr, _
                                                ByVal piDataLength As Short)
        ' 結果表示関数
        Sub crwReceiveDataBCCResult(ByVal ret As Short, _
                                    ByVal bpResData As IntPtr, _
                                    ByVal piDataLength As Short)

            Dim ResData As String

            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & ReceiveDataBCC.Text & Chr(&H22S)

            ' BSTR -> Stringへの変換
            ResData = ConvertAnsiBSTRToString(bpResData)
            DeleteAnsiBSTR(bpResData)

            Marshal.FreeBSTR(bpResData)  ' BSTR開放

            ' 関数実行結果を表示
            rdbccResData.Text = ResData
            ToolTip1.SetToolTip(rdbccResData, ResData)
            rdbccResDataLen.Text = CStr(piDataLength)

            ' 処理結果表示(ボタンのテキストを指定)
            DisplayResult(ret, ReceiveDataBCC.Text)

        End Sub

        ' 結果表示関数呼出し
        Sub crwReceiveDataBCCResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwReceiveDataBCCFunction = CType(crwFunction, CrwReceiveDataBCCFunction)
            Me.BeginInvoke(New CrwReceiveDataBCCResultHandler(AddressOf crwReceiveDataBCCResult), _
                           New Object() {f._ret, _
                                         f._bpResDATA, _
                                         f._piDataLength})
        End Sub

#End Region

#Region "(14) 受信バッファクリア処理 crwComRXBufferClear()"
        Public Sub ComRXBufferClear_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles ComRXBufferClear.Click
            Dim iPortNo As Short

            'ポート番号
            iPortNo = CShort(Val(rbdPortNo.Text))

            '処理結果メッセージ初期化
            Call RetMsgInitialize()

            '「crwComRXBufferClear」ボタン無効
            ComRXBufferClear.Enabled = False

            '受信バッファクリア処理実行
            'ret = crwComRXBufferClear(iPortNo)
            Me.CallCrwFunction( _
                    New CrwComRXBufferClearFunction( _
                            iPortNo, _
                            AddressOf crwComRXBufferClearResultInvoker _
                    ) _
            )

            '「crwComRXBufferClear」ボタン有効
            ComRXBufferClear.Enabled = True
            ComRXBufferClear.Select()


        End Sub

        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwComRXBufferClearResultHandler(ByVal ret As Short)

        ' 結果表示関数
        Sub crwComRXBufferClearResult(ByVal ret As Short)

            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & ComRXBufferClear.Text & Chr(&H22S)

            '各関数のText領域初期化
            If ret = RET_CRW_SUCCESS Then
                '-- crwSendCommandRR -------
                scrCOMSTS.Text = ""
                scrERRSEN.Text = ""
                scrResDATA.Text = ""
                '-- crwReceiveResponse -----
                rrCOMSTS.Text = ""
                rrERRSEN.Text = ""
                rrResDATA.Text = ""
                '-- crwReceiveData ---------
                rdResData.Text = ""
                '-- crwReceiveBinaryData ---
                rbdResData.Text = ""
                '-- crwSendDataRR ----------
                sdrrResData.Text = ""
                '-- ReceiveDataBCC ---------
                rdbccResData.Text = ""
            End If

            DisplayResult(ret, "crwComRXBufferClear")


        End Sub

        ' 結果表示関数呼出し
        Sub crwComRXBufferClearResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwComRXBufferClearFunction = CType(crwFunction, CrwComRXBufferClearFunction)
            Me.BeginInvoke(New CrwComRXBufferClearResultHandler(AddressOf crwComRXBufferClearResult), _
                           New Object() {f._ret})
        End Sub

#End Region

#Region "(15) バイナリデータ送信関数 crwSendBinaryDataQR"
        Private Sub SendBinaryDataQR_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles SendBinaryDataQR.Click

            Dim i As Object
            Dim j As Short
            Dim lpSendData() As Byte
            Dim iSendDataLen As Short
            Dim byt1 As Byte
            Dim str1 As String

            '処理結果メッセージ初期化
            Call RetMsgInitialize()

            '初期化処理
            SendFlag = 0

            If Len(sbdqSendData.Text) Mod 2 <> 0 Then
                MsgBox("偶数ではありません")
            Else
                '送信データ編集処理 ASCII→ﾊﾞｲﾅﾘ変換("0123"→00h 01h 02h 03h)
                RetVal.Text = ""
                If sbdqSendData.Text <> "" Then
                    iSendDataLen = Len(sbdqSendData.Text) / 2
                    ReDim lpSendData(iSendDataLen)
                    'j = 1
                    j = 0
                    For i = 1 To Len(sbdqSendData.Text) Step 2
                        System.Diagnostics.Debug.Write(Mid(sbdqSendData.Text, i, 2))
                        str1 = Mid(sbdqSendData.Text, i, 2)
                        byt1 = CByte("&H" & str1)
                        lpSendData(j) = byt1
                        j = j + 1
                    Next
                    Debug.Print("")
                Else
                    ReDim lpSendData(1)
                End If

                '「crwSendBinaryDataQR」ボタン無効
                SendBinaryDataQR.Enabled = False
                SendBinaryDataQR.Select()

                'バイナリデータ送信関数QR実行
                'ret = crwSendBinaryDataQR(CShort(Val(sbdqPortNo.Text)), CInt(Val(sbdqTimeOut.Text)), CShort(Val(sbdqDSRCheck.Text)), CShort(Val(sbdqCTSCheck.Text)), lpSendData, iSendDataLen)
                Me.CallCrwFunction( _
                        New CrwSendBinaryDataQRFunction( _
                                CShort(Val(sbdqPortNo.Text)), _
                                CInt(Val(sbdqTimeOut.Text)), _
                                CShort(Val(sbdqDSRCheck.Text)), _
                                CShort(Val(sbdqCTSCheck.Text)), _
                                lpSendData, _
                                iSendDataLen, _
                                AddressOf crwSendBinaryDataQRResultInvoker _
                        ) _
                )

                '「crwSendBinaryDataQR」ボタン有効
                SendBinaryDataQR.Enabled = True

            End If
        End Sub

        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwSendBinaryDataQRResultHandler(ByVal ret As Short, _
                                                   ByVal iPortNo As Short)

        ' 結果表示関数
        Sub crwSendBinaryDataQRResult(ByVal ret As Short, _
                                        ByVal iPortNo As Short)

            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & SendBinaryDataQR.Text & Chr(&H22S)


            ' 処理結果表示
            DisplayResult(ret, SendBinaryDataQR.Text)


            '処理結果メッセージ表示
            DisplayResult(ret, SendBinaryDataQR.Text)

            '正常終了の場合
            If ret = RET_CRW_SUCCESS Then
                'バイナリデータ受信関数(crwReceiveBinaryData)を選択
                If OpSendBinaryDataQR(1).Checked = True Then
                    ReceiveBinaryData.Enabled = False
                    If Val(TxtTimeSendBinaryDataQR.Text) <> 0 Then
                        PauseTimems = Val(TxtTimeSendBinaryDataQR.Text) / 1000
                        Debug.Print("PauseTimems = " & PauseTimems & "s")
                        Pause(PauseTimems)
                    End If
                    'バイナリデータ受信関数実行
                    ReceiveBinaryData_Click(ReceiveBinaryData, New System.EventArgs())
                    ReceiveBinaryData.Enabled = True

                    '通信イベントハンドラ登録関数(crwSetCommEventProc)を選択
                ElseIf OpSendBinaryDataQR(2).Checked = True Then
                    SSTab1.SelectedIndex = 3
                    SetCommEventProc.Enabled = False
                    cepCheckAll.CheckState = System.Windows.Forms.CheckState.Unchecked 'ALL Events = OFF
                    cepCheck(0).CheckState = System.Windows.Forms.CheckState.Checked 'EVT_CRW_RXCHAR
                    cepCheck(2).CheckState = System.Windows.Forms.CheckState.Checked 'EVT_CRW_ERR_FRAME
                    cepCheck(3).CheckState = System.Windows.Forms.CheckState.Checked 'EVT_CRW_ERR_OVERRUN
                    cepCheck(4).CheckState = System.Windows.Forms.CheckState.Checked 'EVT_CRW_ERR_PARITY
                    cepCheck(6).CheckState = System.Windows.Forms.CheckState.Checked 'EVT_CRW_DSR
                    cepCheck(8).CheckState = System.Windows.Forms.CheckState.Checked 'EVT_CRW_BREAK
                    cepEntry.Checked = True                 'コールバック登録
                    _OpEVT_RXCHAR_Return_3.Checked = True   'crwReceiveBinaryDataをチェック
                    'Wait Timer
                    If Val(TxtTimeSendBinaryDataQR.Text) <> 0 Then
                        PauseTimems = Val(TxtTimeSendBinaryDataQR.Text) / 1000
                        Debug.Print("PauseTimems = " & PauseTimems & "s")
                        Pause(PauseTimems)
                    End If
                    '通信イベントハンドラ登録関数実行
                    SetCommEventProc_Click(SetCommEventProc, New System.EventArgs())
                    SetCommEventProc.Enabled = True
                End If
            End If

        End Sub

        ' 結果表示関数呼出し
        Sub crwSendBinaryDataQRResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwSendBinaryDataQRFunction = CType(crwFunction, CrwSendBinaryDataQRFunction)
            Me.BeginInvoke(New CrwSendBinaryDataQRResultHandler(AddressOf crwSendBinaryDataQRResult), _
                           New Object() {f._ret, _
                                         f._iPortNo})
        End Sub

#End Region

#Region "(16) バイナリデータ受信関数 crwReceiveBinaryData()"
        Public Sub ReceiveBinaryData_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles ReceiveBinaryData.Click
            Dim lpReceiveData() As Byte
            Dim iReceiveDataLen2 As Short

            '初期化
            SendFlag = 0
            rbdResData.Text = ""
            rbdDataLenRes.Text = ""

            If rbdResDataLen.Text <> 0 Then
                ReDim lpReceiveData(CInt(Val(rbdResDataLen.Text)))
            Else
                ReDim lpReceiveData(1)
            End If

            '処理結果メッセージ初期化
            Call RetMsgInitialize()

            '「crwReceiveBinaryData」ボタン無効
            ReceiveBinaryData.Enabled = False

            ''''' ここから '''''
            'バイナリデータ受信関数
#If 0 Then ' 削除待ち
                ret = crwReceiveBinaryData(CShort(Val(rbdPortNo.Text)), _
                                           CInt(Val(rbdTimeOut.Text)), _
                                           CShort(Val(rbdDSRCheck.Text)), _
                                           lpData, _
                                           CShort(Val(rbdResDataLen.Text)), _
                                           iReceiveDataLen2)
#End If
            Me.CallCrwFunction( _
                    New CrwReceiveBinaryDataFunction( _
                            CShort(Val(rbdPortNo.Text)), _
                            CInt(Val(rbdTimeOut.Text)), _
                            CShort(Val(rbdDSRCheck.Text)), _
                            lpReceiveData, _
                            CShort(Val(rbdResDataLen.Text)), _
                            iReceiveDataLen2, _
                            AddressOf crwReceiveBinaryDataResultInvoker _
                    ) _
            )
            ''''' ここまで '''''

            '「crwReceiveBinaryData」ボタン有効
            ReceiveBinaryData.Enabled = True
            ReceiveBinaryData.Select()


        End Sub

        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwReceiveBinaryDataResultHandler(ByVal ret As Short, _
                                                   ByVal lpData() As Byte, _
                                                   ByRef piDataLength As Short)

        ' 結果表示関数
        Sub crwReceiveBinaryDataResult(ByVal ret As Short, _
                                       ByVal lpData() As Byte, _
                                       ByRef piDataLength As Short)

            Dim lpReceiveData() As Byte
            Dim i As Short
            Dim str2 As String
            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & ReceiveBinaryData.Text & Chr(&H22S)

            str2 = ""

            '受信データを返却するエリア(本関数内用)の設定
            If CDbl(rbdResDataLen.Text) <> 0 Then
                ReDim lpReceiveData(CShort(Val(rbdResDataLen.Text)))
            Else
                ReDim lpReceiveData(1)
            End If

            '実行結果を表示
            'For i = 1 To iReceiveDataLen2
            For i = 0 To piDataLength - 1
                str2 = str2 & VB.Right("0" & Hex(lpData(i)), 2)
            Next

            rbdResData.Text = str2
            ToolTip1.SetToolTip(rbdResData, str2)
            rbdDataLenRes.Text = CStr(piDataLength)

            '実行結果メッセージを表示
            DisplayResult(ret, ReceiveBinaryData.Text)



        End Sub

        ' 結果表示関数呼出し
        Sub crwReceiveBinaryDataResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwReceiveBinaryDataFunction = CType(crwFunction, CrwReceiveBinaryDataFunction)
            Me.BeginInvoke(New CrwReceiveBinaryDataResultHandler(AddressOf crwReceiveBinaryDataResult), _
                           New Object() {f._ret, _
                                         f._lpData, _
                                         f._piDataLength})
        End Sub

#End Region

#Region "(17) レスポンス受信イベントハンドラ登録関数 crwSetResponseEventProc()"
        Private Sub SetResponseEventProc_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles SetResponseEventProc.Click
            Dim lEvent As Integer

            '処理結果メッセージ初期化
            Call RetMsgInitialize()

            If repCheckAll.CheckState = 1 Then
                '全イベント有効
                lEvent = EVT_RSP_CRW_ALL
            Else
                '個別イベントの設定
                lEvent = &H0
                If _repCheck_0.CheckState = 1 Then
                    lEvent = lEvent + EVT_RSP_CRW_RESPONSE
                End If
                If _repCheck_1.CheckState = 1 Then
                    lEvent = lEvent + EVT_RSP_CRW_READY
                End If
                If _repCheck_2.CheckState = 1 Then
                    lEvent = lEvent + EVT_RSP_CRW_BUSY
                End If
                If _repCheck_3.CheckState = 1 Then
                    lEvent = lEvent + EVT_RSP_CRW_ERR_RES_TIMEOUT
                End If
                If _repCheck_4.CheckState = 1 Then
                    lEvent = lEvent + EVT_RSP_CRW_ERR_CTS_TIMEOUT
                End If
                If _repCheck_5.CheckState = 1 Then
                    lEvent = lEvent + EVT_RSP_CRW_ERR_DSR
                End If
                If _repCheck_6.CheckState = 1 Then
                    lEvent = lEvent + EVT_RSP_CRW_ERR_BCC_RETRY
                End If
                If _repCheck_7.CheckState = 1 Then
                    lEvent = lEvent + EVT_RSP_CRW_ERR_COMM_WRITE
                End If
                If _repCheck_8.CheckState = 1 Then
                    lEvent = lEvent + EVT_RSP_CRW_ERR_COMM_READ
                End If
                If _repCheck_9.CheckState = 1 Then
                    lEvent = lEvent + EVT_RSP_CRW_CANCELED
                End If
            End If
            Debug.Print("Wait EVENT :" & Hex(lEvent))

            'New Byte(piDataLength - 1) {}

            If repEntry.Checked = True Then
                'コールバック関数登録
                SetResponseEventProc.Enabled = False
                myCallBack = AddressOf ResponseEvent 'crwResponseEventProc ' コールバック関数生成
                ResponseEventCallBack = AddressOf ResponseEvent '古いほう
                ''ret = crwSetResponseEventProc(CShort(Val(repPortNo.Text)), CShort(Val(repRecMode.Text)), CInt(Val(repTimeOut.Text)), AddressOf CallBackEvent.ResponseEvent, 0, lEvent)
                'ret = crwSetResponseEventProc(CShort(Val(repPortNo.Text)), CShort(Val(repRecMode.Text)), CInt(Val(repTimeOut.Text)), ResponseEventCallBack, 0, lEvent)
                Me.CallCrwFunction( _
                        New CrwSetResponseEventProcFunction( _
                                CShort(Val(repPortNo.Text)), _
                                CShort(Val(repRecMode.Text)), _
                                CInt(Val(repTimeOut.Text)), _
                                myCallBack, _
                                0, _
                                lEvent, _
                                AddressOf crwSetResponseEventProcResultInvoker _
                        ) _
                )
                SetResponseEventProc.Enabled = True

            ElseIf repCancel.Checked = True Then
                'コールバック関数登録解除
                SetResponseEventProc.Enabled = False
                'ret = crwSetResponseEventProc(CShort(Val(repPortNo.Text)), CShort(Val(repRecMode.Text)), CInt(Val(repTimeOut.Text)), Nothing, 0, lEvent)
                Me.CallCrwFunction( _
                        New CrwSetResponseEventProcFunction( _
                                CShort(Val(repPortNo.Text)), _
                                CShort(Val(repRecMode.Text)), _
                                CInt(Val(repTimeOut.Text)), _
                                Nothing, _
                                0, _
                                lEvent, _
                                AddressOf crwSetResponseEventProcResultInvoker _
                        ) _
                )
                SetResponseEventProc.Enabled = True
                SetResponseEventProc.Select()

            End If
        End Sub


        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwSetResponseEventProcResultHandler(ByVal ret As Short)

        ' 結果表示関数
        Sub crwSetResponseEventProcResult(ByVal ret As Short)

            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & SetResponseEventProc.Text & Chr(&H22S)
            '処理結果メッセージ表示
            DisplayResult(ret, SetResponseEventProc.Text)
            SetResponseEventProc.Select()
        End Sub

        ' 結果表示関数呼出し
        Sub crwSetResponseEventProcResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwSetResponseEventProcFunction = CType(crwFunction, CrwSetResponseEventProcFunction)
            Me.BeginInvoke(New CrwSetResponseEventProcResultHandler(AddressOf crwSetResponseEventProcResult), _
                           New Object() {f._ret})
        End Sub
#End Region

#Region "       レスポンス受信コールバック関数"
        ' C#のソースを移したもの、VBに前からあった動作とは異なるResponseEvent参照
        Public Function crwResponseEventProc(ByVal iPortNo As Short, _
                                                    ByVal lEvent As Integer, _
                                                    ByVal lpData As String, _
                                                    ByVal iDataLength As Short, _
                                                    ByVal pParam As Integer) As Short

            Dim msg As String
            Dim pno As String = iPortNo.ToString()
            Dim evt As String = lEvent.ToString()
            Dim dlen As String = iDataLength.ToString()

            msg = "iPortNo = " + pno + " lEvent = " + evt + " lpData = " + lpData + " iDataLength = " + dlen
            MessageBox.Show(msg, "CallBack結果")

            Return 0
        End Function
#End Region

#Region "(18) 通信イベントハンドラ登録関数 crwSetCommEventProc()"
        Private Sub SetCommEventProc_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles SetCommEventProc.Click
            Dim ret As Short
            Dim lEvent As Integer

            '処理結果メッセージ初期化
            Call RetMsgInitialize()

            '全イベントを有効化
            If cepCheckAll.CheckState = 1 Then
                lEvent = EVT_BIN_CRW_ALL
            Else
                '個別イベントの設定
                lEvent = &H0
                If cepCheck(0).CheckState = 1 Then
                    lEvent = lEvent + EVT_CRW_RXCHAR
                End If
                If cepCheck(1).CheckState = 1 Then
                    lEvent = lEvent + EVT_CRW_TXEMPTY
                End If
                If cepCheck(2).CheckState = 1 Then
                    lEvent = lEvent + EVT_CRW_ERR_FRAME
                End If
                If cepCheck(3).CheckState = 1 Then
                    lEvent = lEvent + EVT_CRW_ERR_OVERRUN
                End If
                If cepCheck(4).CheckState = 1 Then
                    lEvent = lEvent + EVT_CRW_ERR_PARITY
                End If
                If cepCheck(5).CheckState = 1 Then
                    lEvent = lEvent + EVT_CRW_CTS
                End If
                If cepCheck(6).CheckState = 1 Then
                    lEvent = lEvent + EVT_CRW_DSR
                End If
                If cepCheck(7).CheckState = 1 Then
                    lEvent = lEvent + EVT_CRW_RLSD
                End If
                If cepCheck(8).CheckState = 1 Then
                    lEvent = lEvent + EVT_CRW_BREAK
                End If
                If cepCheck(9).CheckState = 1 Then
                    lEvent = lEvent + EVT_CRW_RING
                End If
            End If
            Debug.Print("Wait EVENT :" & Hex(lEvent))

            If cepEntry.Checked = True Then
                'コールバック関数登録処理
                CommEventCallBack = AddressOf CommEvent 'スレッド実装前
                myCallBack3 = AddressOf CommEvent

                SetCommEventProc.Enabled = False

                Me.CallCrwFunction( _
                        New CrwSetCommEventProcFunction( _
                                CShort(Val(cepPortNo.Text)), _
                                myCallBack3, _
                                0, _
                                lEvent, _
                                AddressOf crwSetCommEventProcResultInvoker _
                        ) _
                )
                SetCommEventProc.Enabled = True

            ElseIf cepCancel.Checked = True Then
                'コールバック関数解除処理
                SetCommEventProc.Enabled = False
                Me.CallCrwFunction( _
                        New CrwSetCommEventProcFunction( _
                                CShort(Val(cepPortNo.Text)), _
                                Nothing, _
                                0, _
                                lEvent, _
                                AddressOf crwSetCommEventProcResultInvoker _
                        ) _
                )
                SetCommEventProc.Enabled = True
                SetCommEventProc.Select()

            End If

            '処理結果メッセージ表示
            DisplayResult(ret, SetCommEventProc.Text)
        End Sub

        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwSetCommEventProcResultHandler(ByVal ret As Short, _
                                                   ByVal iPortNo As Short, _
                                                   ByVal pCommEventProc As CallBack3)

        ' 結果表示関数
        Sub crwSetCommEventProcResult(ByVal ret As Short, _
                                   ByVal iPortNo As Short, _
                                   ByVal pCommEventProc As CallBack3)

            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & SetCommEventProc.Text & Chr(&H22S)


            ' 処理結果表示
            DisplayResult(ret, SetCommEventProc.Text)
            SetCommEventProc.Select()
        End Sub

        ' 結果表示関数呼出し
        Sub crwSetCommEventProcResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwSetCommEventProcFunction = CType(crwFunction, CrwSetCommEventProcFunction)
            Me.BeginInvoke(New CrwSetCommEventProcResultHandler(AddressOf crwSetCommEventProcResult), _
                           New Object() {f._ret, _
                                         f._iPortNo, _
                                         f._pCommEventProc})
        End Sub
#End Region

#Region "       通信イベントコールバック関数"
#If 0 Then ' 実装前
        Public Function crwCallBackCommEventProc(ByVal iPortNo As Short, _
                                                    ByVal lBufferLength As Integer, _
                                                    ByVal lEvent As Integer, _
                                                    ByVal pParam As Integer) As Short

            Dim i As Short
            Dim msg As String
            Dim pno As String = iPortNo.ToString()


            Dim lpReceiveData() As Byte
            '受信データを返却するエリア(本関数内用)の設定
            If CDbl(rbdResDataLen.Text) <> 0 Then
                'ReDim lpReceiveData(CShort(Val(rbdResDataLen.Text)))
                ReDim lpReceiveData(iDataLength)
            Else
                ReDim lpReceiveData(1)
            End If

            ' 文字の長さ分確保
            lpReceiveData = New Byte(iDataLength - 1) {}
            ' DLLからVBに文字列をコピー            
            If lpData <> 0 Then 'null以外の場合コピー
                Marshal.Copy(lpData, lpReceiveData, 0, iDataLength)
            End If

            msg = "iPortNo = " + pno + " lEvent = " + evt + " iDataLength = " + dlen + " lpData = "
            For i = 0 To iDataLength - 1
                msg = msg & VB.Right("0" & Hex(lpReceiveData(i)), 2)
            Next
            MessageBox.Show(msg, "CallBack結果")

            Return 0
        End Function
#End If
#End Region

#Region "(19) IB Image Data 作成＆送信関数 crwIBBinarySend()"
        '''
        ''' <summary>
        ''' (19) IB Image Data 作成＆送信関数 crwIBBinarySend()
        ''' </summary>
        Private Sub IBBinarySend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IBBinarySend.Click
            Dim iPortNo As Short
            Dim iRetryCount As Short
            Dim iDSRCheck As Short
            Dim iCTSCheck As Short
            Dim iWidth As Short
            Dim iHeith As Short
            Dim iStartY As Short
            Dim lTimeOut As Integer
            Dim lComBufferSize As Integer
            Dim strPathFileName As String
            Dim COMSTS As String
            Dim ERRSEN As String

            'BSTR初期化
            Dim ComStsBSTR As IntPtr = ConvertStringToAnsiBSTR(String.Empty)
            Dim ErrSenBSTR As IntPtr = ConvertStringToAnsiBSTR(String.Empty)

            SendFlag = 0

            ibbsCOMSTS.Text = ""
            ibbsERRSEN.Text = ""
            COMSTS = ""
            ERRSEN = ""

            Call RetMsgInitialize()

            iPortNo = CShort(Val(ibbsPortNo.Text))
            iRetryCount = CShort(Val(ibbsRetryCount.Text))
            iDSRCheck = CShort(Val(ibbsDSRCheck.Text))
            iCTSCheck = CShort(Val(ibbsCTSCheck.Text))
            iWidth = CShort(Val(ibbsWidth.Text))
            iHeith = CShort(Val(ibbsHeith.Text))
            iStartY = CShort(Val(ibbsStartY.Text))
            lTimeOut = Integer.Parse(ibbsTimeOut.Text)
            lComBufferSize = Integer.Parse(ibbsComBufferSize.Text)
            strPathFileName = Trim(ibbsstrPathFileName.Text)

            IBBinarySend.Enabled = False

            ' コマンド送受信関数実行
            'ret = crwIBBinarySend(iPortNo, iRetryCount, iDSRCheck, iCTSCheck, iWidth, iHeith, iStartY, lTimeOut, lComBufferSize, strPathFileName, ComStsBSTR, ErrSenBSTR)
            Me.CallCrwFunction( _
                    New CrwIBBinarySendFunction( _
                            iPortNo, _
                            iRetryCount, _
                            iDSRCheck, _
                            iCTSCheck, _
                            iWidth, _
                            iHeith, _
                            iStartY, _
                            lTimeOut, _
                            lComBufferSize, _
                            strPathFileName, _
                            ComStsBSTR, _
                            ErrSenBSTR, _
                            AddressOf crwIBBinarySendResultInvoker _
                    ) _
            )
            ' フォーカスを戻す
            IBBinarySend.Select()
            IBBinarySend.Enabled = True
            ' フォーカスを戻す
            IBBinarySend.Select()

        End Sub

        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwIBBinarySendResultHandler(ByVal ret As Short, _
                                                   ByVal bpCOMSTS As IntPtr, _
                                                   ByVal bpERRSEN As IntPtr)

        ' 結果表示関数
        Sub crwIBBinarySendResult(ByVal ret As Short, _
                                   ByVal bpCOMSTS As IntPtr, _
                                   ByVal bpERRSEN As IntPtr)


            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & IBBinarySend.Text & Chr(&H22S)
            If ret = 0 Then    ' 結果が正常な場合
                ' 実行結果の表示
                ibbsCOMSTS.Text = ConvertAnsiBSTRToString(bpCOMSTS)
                ibbsERRSEN.Text = ConvertAnsiBSTRToString(bpERRSEN)
            End If
            RetVal.Text = ret.ToString()

            Marshal.FreeBSTR(bpCOMSTS)  ' BSTR開放
            Marshal.FreeBSTR(bpERRSEN)  ' BSTR開放
            ' 関数処理結果表示
            DisplayResult(ret, IBBinarySend.Text)
            ' フォーカスを戻す
            IBBinarySend.Select()
        End Sub

        ' 結果表示関数呼出し
        Sub crwIBBinarySendResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwIBBinarySendFunction = CType(crwFunction, CrwIBBinarySendFunction)
            Me.BeginInvoke(New CrwIBBinarySendResultHandler(AddressOf crwIBBinarySendResult), _
                           New Object() { _
                                        f._ret, _
                                        f._bpCOMSTS, _
                                        f._bpERRSEN})
        End Sub

#End Region

#Region "(20) PI Image Data 作成＆送信関数 crwPIDataSend()"
        '''
        ''' <summary>
        ''' (20) PI Image Data 作成＆送信関数 crwPIDataSend()
        ''' </summary>
        Private Sub PIDataSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PIDataSend.Click
            Dim iPortNo As Short
            Dim iRetryCount As Short
            Dim iDSRCheck As Short
            Dim iCTSCheck As Short
            Dim iWidth As Short
            Dim iHeith As Short
            Dim iStartX As Short
            Dim iStartY As Short
            Dim lTimeOut As Integer
            Dim lComBufferSize As Integer
            Dim strPathFileName As String
            Dim COMSTS As String = ""
            Dim ERRSEN As String = ""

            'BSTR初期化
            Dim ComStsBSTR As IntPtr = ConvertStringToAnsiBSTR(String.Empty)
            Dim ErrSenBSTR As IntPtr = ConvertStringToAnsiBSTR(String.Empty)

            SendFlag = 0

            pidsCOMSTS.Text = ""
            pidsERRSEN.Text = ""
            COMSTS = ""
            ERRSEN = ""

            Call RetMsgInitialize()

            iPortNo = CShort(Val(pidsPortNo.Text))
            iRetryCount = CShort(Val(pidsRetryCount.Text))
            iDSRCheck = CShort(Val(pidsDSRCheck.Text))
            iCTSCheck = CShort(Val(pidsCTSCheck.Text))
            iWidth = CShort(Val(pidsWidth.Text))
            iHeith = CShort(Val(pidsHeith.Text))
            iStartX = CShort(Val(pidsStartX.Text))
            iStartY = CShort(Val(pidsStartY.Text))
            lTimeOut = Integer.Parse(pidsTimeOut.Text)
            lComBufferSize = Integer.Parse(pidsComBufferSize.Text)
            strPathFileName = pidsstrPathFileName.Text

            PIDataSend.Enabled = False

            ' コマンド送受信関数実行
            'ret = crwIBBinarySend(iPortNo, iRetryCount, iDSRCheck, iCTSCheck, iWidth, iHeith, iStartX, lTimeOut, lComBufferSize, strPathFileName, ComStsBSTR, ErrSenBSTR)
            Me.CallCrwFunction( _
                    New crwPIDataSendFunction( _
                            iPortNo, _
                            iRetryCount, _
                            iDSRCheck, _
                            iCTSCheck, _
                            iWidth, _
                            iHeith, _
                            iStartX, _
                            iStartY, _
                            lTimeOut, _
                            lComBufferSize, _
                            strPathFileName, _
                            ComStsBSTR, _
                            ErrSenBSTR, _
                            AddressOf crwPIDataSendResultInvoker _
                    ) _
            )
            ' フォーカスを戻す
            PIDataSend.Select()
            PIDataSend.Enabled = True
            ' フォーカスを戻す
            PIDataSend.Select()

        End Sub

        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwPIDataSendResultHandler(ByVal ret As Short, _
                                                   ByVal bpCOMSTS As IntPtr, _
                                                   ByVal bpERRSEN As IntPtr)

        ' 結果表示関数
        Sub crwPIDataSendResult(ByVal ret As Short, _
                                   ByVal bpCOMSTS As IntPtr, _
                                   ByVal bpERRSEN As IntPtr)


            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & PIDataSend.Text & Chr(&H22S)
            If ret = 0 Then    ' 結果が正常な場合
                ' 実行結果の表示
                pidsCOMSTS.Text = ConvertAnsiBSTRToString(bpCOMSTS)
                pidsERRSEN.Text = ConvertAnsiBSTRToString(bpERRSEN)
            End If
            RetVal.Text = ret.ToString()

            Marshal.FreeBSTR(bpCOMSTS)  ' BSTR開放
            Marshal.FreeBSTR(bpERRSEN)  ' BSTR開放
            ' 関数処理結果表示
            DisplayResult(ret, PIDataSend.Text)
            ' フォーカスを戻す
            PIDataSend.Select()
        End Sub

        ' 結果表示関数呼出し
        Sub crwPIDataSendResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As crwPIDataSendFunction = CType(crwFunction, crwPIDataSendFunction)
            Me.BeginInvoke(New CrwPIDataSendResultHandler(AddressOf crwPIDataSendResult), _
                           New Object() { _
                                        f._ret, _
                                        f._bpCOMSTS, _
                                        f._bpERRSEN})
        End Sub

#End Region

#Region "(21) 文字コード変換関数  crwCharCodeConv()"
        '''
        ''' <summary>
        ''' (21) 文字コード変換関数  crwCharCodeConv()
        ''' </summary>
        Private Sub CharCodeConv_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CharCodeConv.Click
            Dim iConvMode As Short
            Dim csQConvStr As String

            ' 変換対象値が何も無いときは抜ける。
            If _cahcQConvStr_0.Text = "" Then Exit Sub

            '初期化
            _cahcQConvStr_1.Text = ""

            ' 処理結果初期化
            RetMsgInitialize()

            CharCodeConv.Enabled = False

            ' 関数パラメータ設定
            iConvMode = CShort(Strings.Left(cahcConvMode.Text, 1))
            csQConvStr = _cahcQConvStr_0.Text

            _cahcQConvStr_1.Text = ConvertAnsiBSTRToString(crwCharCodeConv(iConvMode, csQConvStr))

            ' フォーカスを戻す
            CharCodeConv.Select()
            CharCodeConv.Enabled = True
            ' フォーカスを戻す
            CharCodeConv.Select()
        End Sub
#End Region

#Region "(22) JIS/Shift-JIS漢字コード変換関数  crwJISconvSJIS()"
        '''
        ''' <summary>
        ''' (22) JIS/Shift-JIS漢字コード変換関数  crwJISconvSJIS()
        ''' </summary>
        Private Sub JISconvSJIS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles JISconvSJIS.Click
            Dim iConvMode As Short
            Dim csQConvStr As String

            ' 変換対象値が何も無いときは抜ける。
            If _JSJQConvStr_0.Text = "" Then Exit Sub

            '初期化
            _JSJQConvStr_1.Text = ""

            ' 処理結果初期化
            RetMsgInitialize()

            JISconvSJIS.Enabled = False

            ' 関数パラメータ設定
            iConvMode = CShort(Strings.Left(JSJConvMode.Text, 1))
            csQConvStr = _JSJQConvStr_0.Text

            _JSJQConvStr_1.Text = ConvertAnsiBSTRToString(crwJISconvSJIS(iConvMode, csQConvStr))

            ' フォーカスを戻す
            JISconvSJIS.Select()
            JISconvSJIS.Enabled = True
            ' フォーカスを戻す
            JISconvSJIS.Select()
        End Sub
#End Region

#Region "(23) データ受信イベントハンドラ登録関数 crwSetReceiveDataBCCEventProc()"
        Private Sub SetReceiveDataBCCEventProc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SetReceiveDataBCCEventProc.Click
            Dim lEvent As Integer

            '処理結果メッセージ初期化
            Call RetMsgInitialize()

            If bccChkAll.CheckState = 1 Then
                '全イベント有効
                lEvent = EVT_BCC_CRW_ALL
            Else
                '個別イベントの設定
                lEvent = &H0
                If bccChk_0.CheckState = 1 Then
                    lEvent = lEvent + EVT_BCC_CRW_RESPONSE
                End If
                If bccChk_1.CheckState = 1 Then
                    lEvent = lEvent + EVT_BCC_CRW_ERR_RES_TIMEOUT
                End If
                If bccChk_2.CheckState = 1 Then
                    lEvent = lEvent + EVT_BCC_CRW_ERR_CTS_TIMEOUT
                End If
                If bccChk_3.CheckState = 1 Then
                    lEvent = lEvent + EVT_BCC_CRW_ERR_DSR
                End If
                If bccChk_4.CheckState = 1 Then
                    lEvent = lEvent + EVT_BCC_CRW_ERR_BCC_RETRY
                End If
                If bccChk_5.CheckState = 1 Then
                    lEvent = lEvent + EVT_BCC_CRW_ERR_COMM_WRITE
                End If
                If bccChk_6.CheckState = 1 Then
                    lEvent = lEvent + EVT_BCC_CRW_ERR_COMM_READ
                End If
                If bccChk_7.CheckState = 1 Then
                    lEvent = lEvent + EVT_BCC_CRW_CANCELED
                End If
            End If

            If bccEntry.Checked = True Then
                'コールバック関数登録
                SetReceiveDataBCCEventProc.Enabled = False
                myCallBack4 = AddressOf ReceiveDataBCCEvent
                ReceiveDataBCCEventCallBack = AddressOf ReceiveDataBCCEvent
                Me.CallCrwFunction( _
                        New CrwSetReceiveDataBCCEventProcFunction( _
                                CShort(Val(bccPortNo.Text)), _
                                CShort(Val(bccACKRes.Text)), _
                                CInt(Val(bccTimeOut.Text)), _
                                myCallBack4, _
                                0, _
                                lEvent, _
                                AddressOf crwSetReceiveDataBCCEventProcResultInvoker _
                        ) _
                )
                SetReceiveDataBCCEventProc.Enabled = True

            ElseIf bccCancel.Checked = True Then
                'コールバック関数登録解除
                SetReceiveDataBCCEventProc.Enabled = False
                Me.CallCrwFunction( _
                        New CrwSetReceiveDataBCCEventProcFunction( _
                                CShort(Val(bccPortNo.Text)), _
                                CShort(Val(bccACKRes.Text)), _
                                CInt(Val(bccTimeOut.Text)), _
                                Nothing, _
                                0, _
                                lEvent, _
                                AddressOf crwSetReceiveDataBCCEventProcResultInvoker _
                        ) _
                )
                SetReceiveDataBCCEventProc.Enabled = True
                SetReceiveDataBCCEventProc.Select()

            End If
        End Sub

        ' 結果表示関数のデリゲート宣言
        Delegate Sub CrwSetReceiveDataBCCEventProcResultHandler(ByVal ret As Short)

        ' 結果表示関数
        Sub crwSetReceiveDataBCCEventProcResult(ByVal ret As Short)

            LbRetValue.Text = "ReturnValue:" & Chr(&H20S) & Chr(&H22S) & SetReceiveDataBCCEventProc.Text & Chr(&H22S)
            '処理結果メッセージ表示
            DisplayResult(ret, SetReceiveDataBCCEventProc.Text)
            SetReceiveDataBCCEventProc.Select()
        End Sub

        ' 結果表示関数呼出し
        Sub crwSetReceiveDataBCCEventProcResultInvoker(ByVal crwFunction As CrwFunction)
            Dim f As CrwSetReceiveDataBCCEventProcFunction = CType(crwFunction, CrwSetReceiveDataBCCEventProcFunction)
            Me.BeginInvoke(New CrwSetReceiveDataBCCEventProcResultHandler(AddressOf crwSetReceiveDataBCCEventProcResult), _
                           New Object() {f._ret})
        End Sub

#End Region

#Region "       電文データ受信コールバック関数"
        Public Function crwReceiveDataBCCEventProc(ByVal iPortNo As Short, _
                                                    ByVal lEvent As Integer, _
                                                    ByVal lpData As String, _
                                                    ByVal iDataLength As Short, _
                                                    ByVal pParam As Integer) As Short

            Dim msg As String
            Dim pno As String = iPortNo.ToString()
            Dim evt As String = lEvent.ToString()
            Dim dlen As String = iDataLength.ToString()

            msg = "iPortNo = " + pno + " lEvent = " + evt + " lpData = " + lpData + " iDataLength = " + dlen
            MessageBox.Show(msg, "CallBack結果")

            Return 0
        End Function
#End Region

#Region "Form開始処理"
        Private Sub Form1_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
            Dim strAppVer As String = String.Empty
            Dim strDLLVer As String = String.Empty
            Dim strLog As String = String.Empty

            LoadFlag = True

            'PCardRW64.dllファイルのバージョン情報を取得する()
            Dim hVerInfo As System.Diagnostics.FileVersionInfo = ( _
                System.Diagnostics.FileVersionInfo.GetVersionInfo(".\PCardRW64.dll") _
            )

            'INI File Path 指定
            INIFName = Application.StartupPath & "\PCardRW64.ini"

            'Get App Version
            strAppVer = Application.ProductVersion

            'Get File Version
            strDLLVer &= hVerInfo.FileVersion
            'Get File Version MajorBlock 
            DLLMajor &= hVerInfo.ProductMajorPart

            'Debug.WriteLine("Application.StartupPath = " & Application.StartupPath)
            'Debug.WriteLine("INIFName = " & INIFName)
            'Debug.WriteLine("hVerInfo.FileVersion = " & hVerInfo.FileVersion)
            'Debug.WriteLine("hVerInfo.ProductMajorPart = " & hVerInfo.ProductMajorPart)

            Me.Text = "PCardRW64.Dll 関数Test Program VB2008 Ver:" & strAppVer & " [ DLL Ver:" & strDLLVer & " ]"

            'INI Fileがないとき作る
            If ReadINI("Application", "Name", INIFName) <> "PCardRW64DLL INI File" Then
                Call CreateINI()
            End If

            strLog = ReadINI("Log", "Logging", INIFName)
            Select Case strLog
                Case "-1"
                    CmbLog.SelectedIndex = 0
                Case "0"
                    CmbLog.SelectedIndex = 1
                Case "1"
                    CmbLog.SelectedIndex = 2
                Case "2"
                    CmbLog.SelectedIndex = 3
            End Select
            ToolTip1.SetToolTip(CmbLog, CmbLog.Text)

            opPortNo.SelectedIndex = 0
            opBaudRate.SelectedIndex = 2
            opDataBit.SelectedIndex = 1
            opParity.SelectedIndex = 1

            sdData.Text = ""
            TxtSdDataBin.Text = "0405"
            SendFlag = 0
            repCheckAll.CheckState = System.Windows.Forms.CheckState.Unchecked
            cepCheckAll.CheckState = System.Windows.Forms.CheckState.Unchecked

            'ポート指定(COM1)
            cpPortNo.SelectedIndex = 0
            scrPortNo.SelectedIndex = 0
            scPortNo.SelectedIndex = 0
            rrPortNo.SelectedIndex = 0
            sdPortNo.SelectedIndex = 0
            rdPortNo.SelectedIndex = 0
            sbdqPortNo.SelectedIndex = 0
            rbdPortNo.SelectedIndex = 0
            repPortNo.SelectedIndex = 0
            cepPortNo.SelectedIndex = 0
            sdrrPortNo.SelectedIndex = 0
            sdbccPortNo.SelectedIndex = 0
            rdbccPortNo.SelectedIndex = 0
            crxbcPortNo.SelectedIndex = 0
            pidsPortNo.SelectedIndex = 0
            ibbsPortNo.SelectedIndex = 0

            LoadFlag = False

        End Sub
#End Region

#Region "Form終了処理"
        Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

            Dim PortNo As Short = 0
            'Dim ret As Object
            ' ポートクローズ処理
            If portcount > 0 Then
                For PortNo = 1 To 256 Step 1
                    If portflag(PortNo - 1) = True Then
                        crwClosePort(PortNo)
                    End If
                Next PortNo
            End If
            'ポートクローズ処理
            'Call crwClosePort(CShort(Val(cpPortNo.Text)))
            myWorker1.TerminateThread()
            myWorker2.TerminateThread()
            myWorker3.TerminateThread()
        End Sub
#End Region

        'EVT_CRW_RXCHAR受信時のCall関数 有効/無効切替処理
        Private Sub _cepCheck_0_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _cepCheck_0.CheckedChanged

            If _cepCheck_0.CheckState = CheckState.Checked Then
                'EVT_CRW_RXCHAR 有効
                FrmEVT_RXCHAR_Return.Enabled = True
                _OpEVT_RXCHAR_Return_0.Enabled = True
                _OpEVT_RXCHAR_Return_1.Enabled = True
                _OpEVT_RXCHAR_Return_2.Enabled = True
                _OpEVT_RXCHAR_Return_3.Enabled = True
            Else
                'EVT_CRW_RXCHAR 無効
                FrmEVT_RXCHAR_Return.Enabled = False
                _OpEVT_RXCHAR_Return_0.Enabled = False
                _OpEVT_RXCHAR_Return_1.Enabled = False
                _OpEVT_RXCHAR_Return_2.Enabled = False
                _OpEVT_RXCHAR_Return_3.Enabled = False
            End If
        End Sub

        '全イベント 有効/無効切替処理
        Private Sub cepCheckAll_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cepCheckAll.CheckedChanged

            If cepCheckAll.CheckState = CheckState.Checked Then
                _cepCheck_0.Enabled = False
                _cepCheck_1.Enabled = False
                _cepCheck_2.Enabled = False
                _cepCheck_3.Enabled = False
                _cepCheck_4.Enabled = False
                _cepCheck_5.Enabled = False
                _cepCheck_6.Enabled = False
                _cepCheck_7.Enabled = False
                _cepCheck_8.Enabled = False
                _cepCheck_9.Enabled = False

                FrmEVT_RXCHAR_Return.Enabled = True
                _OpEVT_RXCHAR_Return_0.Enabled = True
                _OpEVT_RXCHAR_Return_1.Enabled = True
                _OpEVT_RXCHAR_Return_2.Enabled = True
                _OpEVT_RXCHAR_Return_3.Enabled = True
            Else
                _cepCheck_0.Enabled = True
                _cepCheck_1.Enabled = True
                _cepCheck_2.Enabled = True
                _cepCheck_3.Enabled = True
                _cepCheck_4.Enabled = True
                _cepCheck_5.Enabled = True
                _cepCheck_6.Enabled = True
                _cepCheck_7.Enabled = True
                _cepCheck_8.Enabled = True
                _cepCheck_9.Enabled = True

                If cepCheck(0).CheckState = CheckState.Checked Then
                    FrmEVT_RXCHAR_Return.Enabled = True
                    _OpEVT_RXCHAR_Return_0.Enabled = True
                    _OpEVT_RXCHAR_Return_1.Enabled = True
                    _OpEVT_RXCHAR_Return_2.Enabled = True
                    _OpEVT_RXCHAR_Return_3.Enabled = True
                Else
                    FrmEVT_RXCHAR_Return.Enabled = False
                    _OpEVT_RXCHAR_Return_0.Enabled = False
                    _OpEVT_RXCHAR_Return_1.Enabled = False
                    _OpEVT_RXCHAR_Return_2.Enabled = False
                    _OpEVT_RXCHAR_Return_3.Enabled = False
                End If
            End If
        End Sub

        'crwSendDataBCC関数にてのイベント設定処理
        Private Sub OpSendDataBCC_CheckedChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles OpSendDataBCC.CheckedChanged
            If eventSender.Checked Then
                Dim Index As Short = OpSendDataBCC.GetIndex(eventSender)
                If OpSendDataBCC(1).Checked = True Then
                    'crwReceiveDataBCC呼出選択
                    sdbccACKCount.Text = CStr(1)
                End If
            End If
        End Sub

        'レスポンス受信イベントハンドラ登録関数(crwSetResponseEventProc)全イベントチェック設定処理
        Private Sub repCheckAll_CheckStateChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles repCheckAll.CheckStateChanged

            If repCheckAll.CheckState = 1 Then
                _repCheck_0.Enabled = False
                _repCheck_1.Enabled = False
                _repCheck_2.Enabled = False
                _repCheck_3.Enabled = False
                _repCheck_4.Enabled = False
                _repCheck_5.Enabled = False
                _repCheck_6.Enabled = False
                _repCheck_7.Enabled = False
                _repCheck_8.Enabled = False
                _repCheck_9.Enabled = False
            Else
                _repCheck_0.Enabled = True
                _repCheck_1.Enabled = True
                _repCheck_2.Enabled = True
                _repCheck_3.Enabled = True
                _repCheck_4.Enabled = True
                _repCheck_5.Enabled = True
                _repCheck_6.Enabled = True
                _repCheck_7.Enabled = True
                _repCheck_8.Enabled = True
                _repCheck_9.Enabled = True
            End If
        End Sub

        'バイナリデータ送信関数QR(crwSendBinaryDataQR)送信データレングス算出
        Private Sub sbdqSendData_TextChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles sbdqSendData.TextChanged
            sbdqSendDataLen.Text = CStr(Len(sbdqSendData.Text) / 2)
            ToolTip1.SetToolTip(sbdqSendData, sbdqSendData.Text)
        End Sub

        'コマンド送信関数(crwSendCommand)送信データレングス算出
        Private Sub scCmdParam_TextChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles scCmdParam.TextChanged
            'scParamLen.Text = CStr(LenB(StrConv(scCmdParam.Text, vbFromUnicode)))
            scParamLen.Text = CStr(CShort(Len(scCmdParam.Text)))
            ToolTip1.SetToolTip(scCmdParam, scCmdParam.Text)
        End Sub

        'コマンド送受信関数(crwSendCommandRR)送信データレングス算出
        Private Sub scrCmdParam_TextChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles scrCmdParam.TextChanged
            'scrParamLen.Text = CStr(LenB(StrConv(scrCmdParam.Text, vbFromUnicode)))
            scrParamLen.Text = CStr(CShort(Len(scrCmdParam.Text)))
            ToolTip1.SetToolTip(scrCmdParam, scrCmdParam.Text)
        End Sub

        '電文データ送信関数(crwSendDataBCC)送信データレングス算出
        Private Sub sdbccSendData_TextChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles sdbccSendData.TextChanged
            sdbccSendDataLen.Text = CStr(Len(sdbccSendData.Text))
            ToolTip1.SetToolTip(sdbccSendData, sdbccSendData.Text)
        End Sub

        'データ送信関数(応答なし)(crwSendDataQR)送信データレングス算出
        Private Sub sdData_TextChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles sdData.TextChanged
            sdDatalen.Text = CStr(Len(sdData.Text))
            ToolTip1.SetToolTip(sdData, sdData.Text)
        End Sub

        '電文データ送受信関数(crwSendDataRR)送信データレングス算出
        Private Sub sdrrSendData_TextChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles sdrrSendData.TextChanged
            sdrrSendDataLen.Text = CStr(Len(sdrrSendData.Text))
            ToolTip1.SetToolTip(sdrrSendData, sdrrSendData.Text)
        End Sub

        '処理結果メッセージ初期化
        Public Sub RetMsgInitialize()
            'リターンコードボックスを初期化します
            RetMsg.BackColor = System.Drawing.ColorTranslator.FromOle(&HFFFFFF)
            RetVal.BackColor = System.Drawing.ColorTranslator.FromOle(&HFFFFFF)
            LbRetValue.Text = "ReturnValue:"

            RetMsg.Text = ""
            RetVal.Text = ""



        End Sub

        '処理結果メッセージ表示処理
        Public Sub DisplayResult(ByVal ret As Short, Optional ByRef FuncName As String = "")
            Dim Work As String

            If FuncName <> "" Then
                ' "FuncName"
                Work = Chr(&H20S) & Chr(&H22S) & FuncName & Chr(&H22S)
                LbRetValue.Text = "ReturnValue:" & Work
            Else
                LbRetValue.Text = "ReturnValue:"
            End If

            RetVal.Text = CStr(ret)

        End Sub

        '処理結果メッセージ判定処理
        Private Sub RetVal_TextChanged(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles RetVal.TextChanged
            If RetVal.Text <> "TRUE" And RetVal.Text <> "FALSE" And RetVal.Text <> "" Then
                Select Case Val(RetVal.Text)
                    Case RET_CRW_SUCCESS, RET_CRW_ACK, RET_CRW_RESPONSE
                        RetMsg.BackColor = System.Drawing.ColorTranslator.FromOle(&HC000) '緑
                        RetMsg.Text = "OK/ACK/RESPONSE"
                        RetVal.BackColor = System.Drawing.ColorTranslator.FromOle(&HC000)
                    Case RET_CRW_FAILURE
                        'RetMsg.BackColor = System.Drawing.ColorTranslator.FromOle(&HC000) '緑
                        RetMsg.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF) '赤
                        RetMsg.Text = "FAILURE/NAK/READY"
                        'RetVal.BackColor = System.Drawing.ColorTranslator.FromOle(&HC000)
                        RetVal.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF) '赤
                    Case RET_CRW_BUSY, RET_CRW_NAK_BINARY
                        RetMsg.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF80FF) '桃色
                        RetMsg.Text = "BUSY/NAK_BINARY"
                        RetVal.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF80FF)
                    Case RET_CRW_ERR_PARAM
                        RetMsg.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF) '赤
                        RetMsg.Text = "PARAM ERR"
                        RetVal.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF)
                    Case RET_CRW_ERR_PORT
                        RetMsg.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF) '赤
                        RetMsg.Text = "PORT ERR"
                        RetVal.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF)
                    Case RET_CRW_ERR_RES_TIMEOUT
                        RetMsg.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF) '赤
                        RetMsg.Text = "RES TIMEOUT"
                        RetVal.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF)
                    Case RET_CRW_ERR_CTS_TIMEOUT
                        RetMsg.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF) '赤
                        RetMsg.Text = "CTS TIMEOUT"
                        RetVal.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF)
                    Case RET_CRW_ERR_DSR_TIMEOUT
                        RetMsg.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF) '赤
                        RetMsg.Text = "DSR ERR"
                        RetVal.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF)
                    Case RET_CRW_ERR_BCC_RETRY
                        RetMsg.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF) '赤
                        RetMsg.Text = "BCC ERR"
                        RetVal.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF)
                    Case RET_CRW_ERR_COMM_WRITE
                        RetMsg.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF) '赤
                        RetMsg.Text = "COMM WRITE ERR"
                        RetVal.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF)
                    Case RET_CRW_ERR_COMM_READ
                        RetMsg.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF) '赤
                        RetMsg.Text = "COMM READ ERR"
                        RetVal.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF)
                    Case RET_CRW_ERR_BUSY
                        RetMsg.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF) '赤
                        RetMsg.Text = "非同期処理実行中！"
                        RetVal.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF)
                    Case Else
                        RetMsg.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF) '赤
                        RetMsg.Text = "OTHER ERR"
                        RetVal.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF)
                End Select
            ElseIf RetVal.Text = "TRUE" Then
                RetVal.BackColor = System.Drawing.ColorTranslator.FromOle(&HC000)
                RetMsg.BackColor = System.Drawing.ColorTranslator.FromOle(&HFFFFFF) '白
                RetMsg.Text = ""
            ElseIf RetVal.Text = "FALSE" Then
                RetVal.BackColor = System.Drawing.ColorTranslator.FromOle(&HFF)
                RetMsg.BackColor = System.Drawing.ColorTranslator.FromOle(&HFFFFFF) '白
                RetMsg.Text = ""
            End If

            System.Windows.Forms.Application.DoEvents()
        End Sub

        '一時停止処理
        Private Sub Pause(ByRef NumSecs As Single)
            '本Subは、指定した時間次の処理を待ちます
            Dim Start, EndTime As Single

            Start = VB.Timer()
            EndTime = Start + NumSecs

            Do
                System.Windows.Forms.Application.DoEvents()
                If Start > VB.Timer() And Start <= EndTime Then
                    EndTime = EndTime - 86400
                End If
            Loop Until VB.Timer() >= EndTime

        End Sub

        'コールバック関数処理(レスポンス受信イベントハンドラ登録用関数)
        Public Function ResponseEvent(ByVal iPortNo As Short, ByVal lEvent As Integer, ByVal bpData As IntPtr, ByVal iDataLen As Short, ByVal pParam As Integer) As Short

            Dim lpData As String
            lpData = Marshal.PtrToStringBSTR(bpData)
            On Error Resume Next
            System.Diagnostics.Debug.Write("Port No." & iPortNo & " " & lEvent)
            Select Case lEvent
                Case EVT_RSP_CRW_RESPONSE
                    Debug.Print(" " & lpData)
                    MsgBox("Port No." & iPortNo & vbCrLf & "[Answer Data]  = " & lpData & vbCrLf & "Receive Length = " & CStr(iDataLen), MsgBoxStyle.Information, "[ReceiveResponseEvent]")
                Case EVT_RSP_CRW_READY
                    Debug.Print(" " & lpData)
                    MsgBox("Port No." & iPortNo & vbCrLf & "[Ready Status] = " & lpData & vbCrLf & "Receive Length = " & CStr(iDataLen), MsgBoxStyle.Information, "[ReceiveResponseEvent]")
                Case EVT_RSP_CRW_BUSY
                    Debug.Print(" " & lpData)
                    MsgBox("Port No." & iPortNo & vbCrLf & "[Busy Status]  = " & lpData & vbCrLf & "Receive Length = " & CStr(iDataLen), MsgBoxStyle.Information, "[ReceiveResponseEvent]")
                Case EVT_RSP_CRW_CANCELED
                    MsgBox("Port No." & iPortNo & vbCrLf & "受信待ち中止！", MsgBoxStyle.Information, "[ReceiveResponseEvent]")
                Case EVT_RSP_CRW_ERR_RES_TIMEOUT
                    MsgBox("Port No." & iPortNo & vbCrLf & "受信待ちタイムアウト!", MsgBoxStyle.Critical, "[ReceiveResponseEvent]")
                Case EVT_RSP_CRW_ERR_CTS_TIMEOUT
                    MsgBox("Port No." & iPortNo & vbCrLf & "CTS ON 待ちタイムアウト！", MsgBoxStyle.Critical, "[ReceiveResponseEvent]")
                Case EVT_RSP_CRW_ERR_DSR
                    MsgBox("Port No." & iPortNo & vbCrLf & "端末がOFFです！", MsgBoxStyle.Critical, "[ReceiveResponseEvent]")
                Case EVT_RSP_CRW_ERR_BCC_RETRY
                    MsgBox("Port No." & iPortNo & vbCrLf & "BCCエラーリトライOVER！", MsgBoxStyle.Critical, "[ReceiveResponseEvent]")
                Case EVT_RSP_CRW_ERR_COMM_WRITE
                    MsgBox("Port No." & iPortNo & vbCrLf & "COM Write Error!", MsgBoxStyle.Critical, "[ReceiveResponseEvent]")
                Case EVT_RSP_CRW_ERR_COMM_READ
                    MsgBox("Port No." & iPortNo & vbCrLf & "COM Read Error!", MsgBoxStyle.Critical, "[ReceiveResponseEvent]")
                Case Else
                    MsgBox("Events : " & lEvent & " ?????", MsgBoxStyle.Critical, "[ReceiveResponseEvent]")
            End Select
        End Function

        'コールバック関数処理(電文データ受信イベントハンドラ登録用関数)
        Public Function ReceiveDataBCCEvent(ByVal iPortNo As Short, _
                                        ByVal lEvent As Integer, _
                                        ByVal bpData As IntPtr, _
                                        ByVal iDataLen As Short, _
                                        ByVal pParam As Integer _
                                        ) As Short

            Dim lpData As String

            lpData = Marshal.PtrToStringBSTR(bpData)
            On Error Resume Next
            System.Diagnostics.Debug.Write("Port No." & iPortNo & " " & lEvent)
            Select Case lEvent
                Case EVT_BCC_CRW_RESPONSE
                    Debug.Print(" " & lpData)
                    MsgBox("正常電文受信 [EVT_BCC_CRW_RESPONSE]" & vbCrLf & "Port No." & iPortNo & vbCrLf & "Answer Data  = " & lpData & vbCrLf & "Receive Length = " & _
                                                            CStr(iDataLen), MsgBoxStyle.Information, "[ReceiveBCCEvent]")
                Case EVT_BCC_CRW_CANCELED
                    MsgBox("Port No." & iPortNo & vbCrLf & "受信待ち中止！ [EVT_BCC_CRW_CANCELED]", MsgBoxStyle.Information, "[ReceiveBCCEvent]")
                Case EVT_BCC_CRW_ERR_RES_TIMEOUT
                    MsgBox("Port No." & iPortNo & vbCrLf & "受信待ちタイムアウト! [EVT_BCC_CRW_ERR_RES_TIMEOUT]", MsgBoxStyle.Critical, "[ReceiveBCCEvent]")
                Case EVT_BCC_CRW_ERR_CTS_TIMEOUT
                    MsgBox("Port No." & iPortNo & vbCrLf & "CTS ON 待ちタイムアウト！ [EVT_BCC_CRW_ERR_CTS_TIMEOUT]", MsgBoxStyle.Critical, "[ReceiveBCCEvent]")
                Case EVT_BCC_CRW_ERR_DSR
                    MsgBox("Port No." & iPortNo & vbCrLf & "端末がOFFです！ [EVT_BCC_CRW_ERR_DSR]", MsgBoxStyle.Critical, "[ReceiveBCCEvent]")
                Case EVT_BCC_CRW_ERR_BCC_RETRY
                    MsgBox("Port No." & iPortNo & vbCrLf & "BCCエラーリトライOVER！ [EVT_BCC_CRW_ERR_BCC_RETRY]", MsgBoxStyle.Critical, "[ReceiveBCCEvent]")
                Case EVT_BCC_CRW_ERR_COMM_WRITE
                    MsgBox("Port No." & iPortNo & vbCrLf & "COM Write Error! [EVT_BCC_CRW_ERR_COMM_WRITE]", MsgBoxStyle.Critical, "[ReceiveBCCeEvent]")
                Case EVT_BCC_CRW_ERR_COMM_READ
                    MsgBox("Port No." & iPortNo & vbCrLf & "COM Read Error! [EVT_BCC_CRW_ERR_COMM_READ]", MsgBoxStyle.Critical, "[ReceiveBCCEvent]")
                Case Else
                    MsgBox("Events : " & CStr(Hex(lEvent)) & " ?????", MsgBoxStyle.Critical, "[ReceiveBCCEvent]")
            End Select
        End Function

        'コールバック関数処理(通信イベントハンドラ登録用関数)
        Public Function CommEvent(ByVal iPortNo As Short, ByVal lBufferLen As Integer, ByVal lEvent As Integer, ByVal pParam As Integer) As Short
            Dim rtn As Object
            Dim ret As Short
            Dim rData() As Byte
            Dim rDataLen As Short
            Dim strData As String
            Dim i As Short

            rtn = 0
            On Error Resume Next
            System.Diagnostics.Debug.Write("Port No." & iPortNo & " " & lEvent)
            Select Case lEvent
                Case EVT_CRW_RXCHAR
                    With Me
                        'RetVal.Text = ""
                        'EVT_CRW_RXCHAR受信時のCall関数がtrue And Call関数がNonの時
                        If FrmEVT_RXCHAR_Return.Enabled = True And OpEVT_RXCHAR_Return(0).Checked = False Then

                            If _OpEVT_RXCHAR_Return_1.Checked = True Then 'crwReceiveData
                                SSTab1.SelectedIndex = 1
                                ReceiveData_Click(Nothing, Nothing)

                            ElseIf _OpEVT_RXCHAR_Return_2.Checked = True Then  'crwReceiveDataBCC
                                SSTab1.SelectedIndex = 2
                                ReceiveDataBCC_Click(Nothing, Nothing)

                            ElseIf _OpEVT_RXCHAR_Return_3.Checked = True Then  'crwReceiveBinaryData
                                SSTab1.SelectedIndex = 3
                                ReceiveBinaryData_Click(Nothing, Nothing)

                            End If

                        Else
                            MsgBox("入力バッファにデータを受信しました。", MsgBoxStyle.Information, "[COMEvent]")
                        End If
                    End With

                Case EVT_CRW_TXEMPTY
                    Debug.Print(" 送信完了!")
                    If SendFlag = 1 Then
                        RetVal.Text = ""
                        ResponseEventCallBack = AddressOf ResponseEvent
                        ret = crwSetResponseEventProc(iPortNo, 0, 5000, ResponseEventCallBack, 0, EVT_RSP_CRW_ALL)
                        DisplayResult((ret))
                    Else
                        MsgBox("Port No." & iPortNo & " 送信完了!")
                    End If
                Case EVT_CRW_CANCELED
                    MsgBox("Port No." & iPortNo & vbCrLf & "受信待ち中止！", MsgBoxStyle.Information, "[COMEvent]")
                Case EVT_CRW_ERR_FRAME
                    MsgBox("フレミングエラー！", MsgBoxStyle.Critical, "[COMEvent]")
                Case EVT_CRW_ERR_OVERRUN
                    MsgBox("オーバーランエラー！", MsgBoxStyle.Critical, "[COMEvent]")
                Case EVT_CRW_ERR_PARITY
                    MsgBox("パリティエラー！", MsgBoxStyle.Critical, "[COMEvent]")
                Case EVT_CRW_CTS
                    Debug.Print(" CTR ")
                    MsgBox("CTS Line Change!", MsgBoxStyle.Critical, "[COMEvent]")
                Case EVT_CRW_DSR
                    Debug.Print(" DSR OFF")
                    If MsgBox("DSR が OFF になりました！" & vbCrLf & vbCrLf & "ポートをクローズしますか？", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "[COMEvent]") = MsgBoxResult.Yes Then
                        ret = crwClosePort(iPortNo)
                        If rtn = RET_CRW_SUCCESS Then
                            MsgBox("ポートをクローズしました！", MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "[COMEvent]")
                        End If
                    End If
                Case EVT_CRW_RLSD
                    Debug.Print(" RLSD ")
                    MsgBox("RLSD Change!", MsgBoxStyle.Critical, "[COMEvent]")
                Case EVT_CRW_BREAK
                    Debug.Print(" BREAK ")
                    ret = crwClosePort(iPortNo)
                    MsgBox("Port No." & iPortNo & vbCrLf & "Break信号検出!" & vbCrLf & "Port:" & iPortNo & " Close!!", MsgBoxStyle.Critical, "[COMEvent]")
                Case EVT_CRW_RING
                    Debug.Print(" RING ")
                    MsgBox("RING!", MsgBoxStyle.Critical, "[COMEvent]")
                Case Else
                    MsgBox("Events : " & lEvent & " ?????", MsgBoxStyle.Critical, "[COMEvent]")
            End Select
        End Function

#Region "　Right メソッド　"

        ''' -----------------------------------------------------------------------------------
        ''' <summary>
        '''     文字列の右端から指定された文字数分の文字列を返します。</summary>
        ''' <param name="stTarget">
        '''     取り出す元になる文字列。</param>
        ''' <param name="iLength">
        '''     取り出す文字数。</param>
        ''' <returns>
        '''     右端から指定された文字数分の文字列。
        '''     文字数を超えた場合は、文字列全体が返されます。</returns>
        ''' -----------------------------------------------------------------------------------
        Public Shared Function Right6(ByVal stTarget As String, ByVal iLength As Integer) As String
            If iLength <= stTarget.Length Then
                Return stTarget.Substring(stTarget.Length - iLength)
            End If

            Return stTarget
        End Function

#End Region

#Region "　LenB メソッド　"

        ''' -----------------------------------------------------------------------------------------
        ''' <summary>
        '''     半角 1 バイト、全角 2 バイトとして、指定された文字列のバイト数を返します。</summary>
        ''' <param name="stTarget">
        '''     バイト数取得の対象となる文字列。</param>
        ''' <returns>
        '''     半角 1 バイト、全角 2 バイトでカウントされたバイト数。</returns>
        ''' -----------------------------------------------------------------------------------------
        Public Shared Function LenB(ByVal stTarget As String) As Integer
            Return System.Text.Encoding.GetEncoding("Shift_JIS").GetByteCount(stTarget)
        End Function

#End Region

#Region "CRW関数呼び出し"
        Private Sub CallCrwFunction(ByVal crwFunction As CrwFunction)

            Dim workerIns As Worker

            workerIns = GetSelectedThread(crwFunction)
#If 0 Then ' WorkerクラスをNothingで比較できないのでGetSelectedThread()で実行する
            If (Convert.ToInt64(workerIns) = Nothing) Then
                crwFunction.CallFunk()
            Else
                workerIns.CallCrwFunction(crwFunction)
            End If
#End If
        End Sub
#End Region

#Region "CRW関数実行スレッド取得"
        Private Function GetSelectedThread(ByVal crwFunction As CrwFunction) As Worker
            ' VBでのNULLはNothing
            If (opThreadMain.Checked) Then       ' 「メイン」ラジオボタンがチェックされている？
                'Return Nothing
                Runningthread.Text = "Main"

                crwFunction.CallFunk()

            End If

            If (opThreadWorker1.Checked) Then    ' 「ワーカスレッド１」ラジオボタンがチェックされている？
                'Return myWorker1
                Runningthread.Text = myWorker1.getName()
                myWorker1.CallCrwFunction(crwFunction)
            End If

            If (opThreadWorker2.Checked) Then   ' 「ワーカスレッド２」ラジオボタンがチェックされている？
                'Return myWorker2
                Runningthread.Text = myWorker2.getName()
                myWorker2.CallCrwFunction(crwFunction)
            End If

            If (opThreadWorker3.Checked) Then    ' 「ワーカスレッド３」ラジオボタンがチェックされている？
                'Return myWorker3
                Runningthread.Text = myWorker3.getName()
                myWorker3.CallCrwFunction(crwFunction)

            End If

            Return Nothing
        End Function
#End Region

        'SendDataバイナリ変換チェックボックス
        Private Sub ChksdDataBin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ChksdDataBin.Click
            If ChksdDataBin.Checked = False Then
                ChksdDataBin.Checked = False
                TxtSdDataBin.Enabled = False
            Else
                ChksdDataBin.Checked = True
                TxtSdDataBin.Enabled = True
            End If
        End Sub

        Private Sub CmbLog_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmbLog.SelectedIndexChanged
            Dim ret As Short
            Dim strLog As String = String.Empty

            'PCardRW64.INI情報を取得する。
            strLog = Trim(ReadINI("Log", "Logging", INIFName))

            'PCardRW64.INIへ書き込む
            WriteINI("Log", "Logging", Trim(VB.Left(CmbLog.Text, 2)), INIFName)

            If strLog <> Trim(VB.Left(CmbLog.Text, 2)) Then
                ret = MsgBox("LOG設定の設定が変更になっており、反映させるには一度アプリケーションを再起動させる必要があります。" & vbCrLf & "終了させる場合は[はい]を、しない場合は[いいえ]をクリックして下さい", MsgBoxStyle.ApplicationModal + MsgBoxStyle.Exclamation + MsgBoxStyle.YesNo)
                If ret = MsgBoxResult.Yes Then
                    Application.Exit()                'Yesだったらすべて終了
                End If
            End If

            ToolTip1 = New ToolTip
            ToolTip1.SetToolTip(CmbLog, CmbLog.Text)
        End Sub

        Private Sub bccChkAll_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bccChkAll.CheckedChanged
            '全イベント 有効/無効切替処理

            If bccChkAll.CheckState = CheckState.Checked Then
                bccChk_0.Enabled = False
                bccChk_1.Enabled = False
                bccChk_2.Enabled = False
                bccChk_3.Enabled = False
                bccChk_4.Enabled = False
                bccChk_5.Enabled = False
                bccChk_6.Enabled = False
                bccChk_7.Enabled = False
            Else
                bccChk_0.Enabled = True
                bccChk_1.Enabled = True
                bccChk_2.Enabled = True
                bccChk_3.Enabled = True
                bccChk_4.Enabled = True
                bccChk_5.Enabled = True
                bccChk_6.Enabled = True
                bccChk_7.Enabled = True
            End If
        End Sub
    End Class

End Namespace
