﻿Imports System.Text
Imports System.Runtime.InteropServices
Imports System.IO

Public Class ApiBasicLogger
    '----------------------------------------
    ' Declaration of global variables
    '----------------------------------------
    Dim g_appid As Short                                    ' ID for application access
    Dim pdelegate_func As PLOGGEREVENTCALLBACK              ' Event notification Delegate
    Dim gCh As GCHandle                                     ' GCHandle for the callback routine
    Dim pfunc As IntPtr                                     ' IntPtr for the callback routine
    Dim g_samplingdata As UInteger                          ' Sampling data number
    Dim g_file_name As String                               ' Sampling data output file name
    Dim SequenceNum As UShort                               ' Sequence number

    Private Sub ApiBasicLogger_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        '----------------------------------------
        ' Update the initial display of device name
        '----------------------------------------
        textBox_DeviceName.Text = "AIO000"
        '----------------------------------------
        ' Create the combobox for screen size
        '----------------------------------------
        comboBox_OpenMode.Items.Add("Minimize")
        comboBox_OpenMode.Items.Add("Normal")
        comboBox_OpenMode.Items.Add("Maximize")
        '----------------------------------------
        ' Change the selection of screen size combobox to Minimize
        '----------------------------------------
        comboBox_OpenMode.SelectedIndex = CInt(LOGGER_PARAM_WINDOW_OFF)
        '----------------------------------------
        ' Initializing global variables
        '----------------------------------------
        g_appid = 0
        g_file_name = "SamplingData.csv"
        g_samplingdata = 1
        SequenceNum = 1
        '----------------------------------------
        ' Initialize the delegate for event notification
        '----------------------------------------
        pdelegate_func = New PLOGGEREVENTCALLBACK(AddressOf CallBackProc)
        '----------------------------------------
        ' Sets the delegate to never be released
        '----------------------------------------
        If (gCh.IsAllocated = False) Then
            gCh = GCHandle.Alloc(pdelegate_func)
        End If
    End Sub

    '================================================================================
    ' It is the process when the LoggerOpenApplication button is clicked
    ' Launch the app and enable access
    '================================================================================
    Private Sub button_LoggerOpenApplication_Click(sender As Object, e As EventArgs) Handles button_LoggerOpenApplication.Click
        Dim device_name As String                         ' Device name
        Dim openmode As UShort                            ' Screen size
        Dim ret As Integer                                ' For return code
        Dim error_string As New StringBuilder("", 256)    ' Error code string

        '----------------------------------------
        ' Get device name from textbox
        '----------------------------------------
        device_name = textBox_DeviceName.Text
        '----------------------------------------
        ' Get screen size from combobox
        '----------------------------------------
        openmode = comboBox_OpenMode.SelectedIndex
        '----------------------------------------
        ' Initialize the application
        '----------------------------------------
        ret = LoggerOpenApplication(device_name, g_appid, openmode)
        '----------------------------------------
        ' Get error string
        '----------------------------------------
        LoggerGetErrorString(ret, error_string)
        '----------------------------------------
        ' Display error code and message
        '----------------------------------------
        textBox_ReturnNum.Text = String.Format("LoggerOpenApplication = {0} : {1} ", ret, error_string)
    End Sub

    '================================================================================
    ' It is the process when the LoggerSetDeviceName button is clicked
    ' Set the device name
    '================================================================================
    Private Sub button_LoggerSetDeviceName_Click(sender As Object, e As EventArgs) Handles button_LoggerSetDeviceName.Click
        Dim device_name As String                         ' Device name
        Dim ret As Integer                                ' For return code
        Dim error_string As New StringBuilder("", 256)    ' Error code string

        '----------------------------------------
        ' Get device name from textbox
        '----------------------------------------
        device_name = textBox_DeviceName.Text
        '----------------------------------------
        ' Set the device name
        '----------------------------------------
        ret = LoggerSetDeviceName(g_appid, device_name)
        '----------------------------------------
        ' Get error string
        '----------------------------------------
        LoggerGetErrorString(ret, error_string)
        '----------------------------------------
        ' Display error code and message
        '----------------------------------------
        textBox_ReturnNum.Text = String.Format("LoggerSetDeviceName = {0} : {1} ", ret, error_string)
    End Sub

    '================================================================================
    ' It is the process when the ...button is clicked (settings file)
    ' Displays a dialog for selecting a configuration file
    '================================================================================
    Private Sub button_SettingSelectFile_Click(sender As Object, e As EventArgs) Handles button_SettingSelectFile.Click
        '----------------------------------------
        ' Do Not check if the file name exists
        '----------------------------------------
        openFileDialog1.CheckFileExists = False
        '----------------------------------------
        ' If the Then file path exists, Set the file path To the initial path In the dialog.
        '----------------------------------------
        If textBox_SettingFile.Text.Length > 0 Then
            openFileDialog1.InitialDirectory = textBox_SettingFile.Text
            openFileDialog1.FileName = openFileDialog1.SafeFileName
            '----------------------------------------
            ' If the file path does not exist, set MyDocuments to the initial path in the dialog
            '----------------------------------------
        Else
            openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
            openFileDialog1.FileName = ""
        End If
        '----------------------------------------
        ' Display the selected path
        '----------------------------------------
        If openFileDialog1.ShowDialog() = DialogResult.OK Then
            textBox_SettingFile.Text = System.IO.Path.GetFullPath(openFileDialog1.FileName)
        End If
    End Sub

    '================================================================================
    ' It is the process when the LoggerImportSettingFile button is clicked
    ' Import the settings file
    '================================================================================
    Private Sub button_LoggerImportSettingFile_Click(sender As Object, e As EventArgs) Handles button_LoggerImportSettingFile.Click
        Dim filepath As String                            ' File path
        Dim ret As Integer                                ' For return code
        Dim error_string As New StringBuilder("", 256)    ' Error code string
        Dim status As UInteger = 0                        ' For status storage

        '----------------------------------------
        ' Get setting file path from the textbox
        '----------------------------------------
        filepath = textBox_SettingFile.Text
        '----------------------------------------
        ' Import the settings file
        '----------------------------------------
        ret = LoggerImportSettingFile(g_appid, filepath, status)
        '----------------------------------------
        ' Get error string
        '----------------------------------------
        LoggerGetErrorString(ret, error_string)
        '----------------------------------------
        ' Display error code and message
        '----------------------------------------
        textBox_ReturnNum.Text = String.Format("LoggerImportSettingFile = {0} : {1} {2}status=0x{3:X16}", ret, error_string, vbCrLf, status)
    End Sub

    '================================================================================
    ' It is the process when the LoggerSetEventSamplingTimes button is clicked
    ' Set the specified sampling count
    '================================================================================
    Private Sub button_LoggerSetEventSamplingTimes_Click(sender As Object, e As EventArgs) Handles button_LoggerSetEventSamplingTimes.Click
        Dim ret As Integer                                ' For return code
        Dim error_string As New StringBuilder("", 256)    ' Error code string
        Dim sampling_times As UInteger = 0                ' For storing the specified sampling count

        '----------------------------------------
        ' Get the specified sampling count from the text box
        '----------------------------------------
        If Not UInteger.TryParse(textBox_SamplingTimes.Text, sampling_times) Then
            sampling_times = 1000
        End If
        '----------------------------------------
        ' Set the specified sampling count
        '----------------------------------------
        ret = LoggerSetEventSamplingTimes(g_appid, sampling_times)
        '----------------------------------------
        ' Get error string
        '----------------------------------------
        LoggerGetErrorString(ret, error_string)
        '----------------------------------------
        ' Display error code and message
        '----------------------------------------
        textBox_ReturnNum.Text = String.Format("LoggerSetEventSamplingTimes = {0} : {1} ", ret, error_string)
    End Sub

    '================================================================================
    ' It is the process when the LoggerGetEventSamplingTimes button is clicked
    ' Get the specified sampling count
    '================================================================================
    Private Sub button_LoggerGetEventSamplingTimes_Click(sender As Object, e As EventArgs) Handles button_LoggerGetEventSamplingTimes.Click
        Dim ret As Integer                                ' For return code
        Dim error_string As New StringBuilder("", 256)    ' Error code string
        Dim sampling_times As UInteger = 0                ' For storing the specified sampling count

        '----------------------------------------
        ' Get the specified sampling count from the text box
        '----------------------------------------
        ret = LoggerGetEventSamplingTimes(g_appid, sampling_times)
        '----------------------------------------
        ' Get error string
        '----------------------------------------
        LoggerGetErrorString(ret, error_string)
        '----------------------------------------
        ' Display error code and message
        '----------------------------------------
        textBox_ReturnNum.Text = String.Format("LoggerGetEventSamplingTimes = {0} : {1} ", ret, error_string)
        '----------------------------------------
        ' If the specified sampling count acquisition function completes successfully
        '----------------------------------------
        If ret = 0 Then
            '----------------------------------------
            ' Update the sampling count
            '----------------------------------------
            textBox_SamplingTimes.Text = sampling_times.ToString()
        End If
    End Sub

    '================================================================================
    ' It is the process when the Logging Start button is clicked
    ' Start the application input and output
    '================================================================================
    Private Sub button_LoggerStartOperation_Click(sender As Object, e As EventArgs) Handles button_LoggerStartOperation.Click
        Dim ret As Integer                                ' For return code
        Dim error_string As New StringBuilder("", 256)    ' Error code string
        Dim status As UInteger = 0                        ' For status storage
        Dim InputType As UShort                           ' Input method
        Dim ChannelNo(255) As UShort                      ' Channel number
        Dim ChName(256 * 256 - 1) As Byte                 ' Channel name
        Dim Range(255) As UShort                          ' Range
		Dim pre_sequence As UShort = 256                  ' Sequence number

        '----------------------------------------
        ' Close file
        '----------------------------------------
        ret = LoggerGraphWindowOperation(g_appid, CType(LOGGER_PARAM_GRAPH_CLOSE, UShort), CType(LOGGER_PARAM_FILE, UShort), 0)
        If Not ret = 0 Then
            '----------------------------------------
            ' Get error string
            '----------------------------------------
            LoggerGetErrorString(ret, error_string)
            '----------------------------------------
            ' Display error code and message
            '----------------------------------------
            textBox_ReturnNum.Text = String.Format("LoggerGraphWindowOperation = {0} : {1} ", ret, error_string)
        End If
        '----------------------------------------
        ' Delete file
        '----------------------------------------
        If File.Exists(g_file_name) Then
            Try
                File.Delete(g_file_name)
            Catch ex As Exception
                textBox_ReturnNum.Text = String.Format("Data file deletion error")
                Exit Sub
            End Try
        End If
        '----------------------------------------
        ' Get the channel settings
        '----------------------------------------
        ret = LoggerGetChannelSetting(g_appid, InputType, pre_sequence, ChannelNo, ChName, Range)
        If Not ret = 0 Then
            '----------------------------------------
            ' Get the error string
            '----------------------------------------
            LoggerGetErrorString(ret, error_string)
            '----------------------------------------
            ' Display the error code and the message
            '----------------------------------------
            textBox_ReturnNum.Text = String.Format("LoggerGetChannelSetting = {0} : {1} ", ret, error_string)
            Exit Sub
        End If
        '----------------------------------------
        ' Initialize the number of sampling data
        '----------------------------------------
        g_samplingdata = 1
        '----------------------------------------
        ' Specify the buffer mode (API acquisition mode)
        '----------------------------------------
        ret = LoggerSetAcquiredMode(g_appid, CType(LOGGER_PARAM_MODE_API, UShort))
        If Not ret = 0 Then
            '----------------------------------------
            ' Get error string
            '----------------------------------------
            LoggerGetErrorString(ret, error_string)
            '----------------------------------------
            ' Display error code and message
            '----------------------------------------
            textBox_ReturnNum.Text = String.Format("LoggerSetAcquiredMode = {0} : {1} ", ret, error_string)
            Exit Sub
        End If
        '----------------------------------------
        ' Get a fixed pointer to the event notification delegate
        '----------------------------------------
        pfunc = Marshal.GetFunctionPointerForDelegate(pdelegate_func)
        '----------------------------------------
        ' Set the event
        '----------------------------------------
        ret = LoggerSetNotifyEvent(g_appid, pfunc, CType(LOGGER_PARAM_EVENT_DATANUM Or LOGGER_PARAM_EVENT_END, UInteger), Nothing)
        If Not ret = 0 Then
            '----------------------------------------
            ' Get error string
            '----------------------------------------
            LoggerGetErrorString(ret, error_string)
            '----------------------------------------
            ' Display error code and message
            '----------------------------------------
            textBox_ReturnNum.Text = String.Format("LoggerSetNotifyEvent = {0} : {1} ", ret, error_string)
            Exit Sub
        End If
        '----------------------------------------
        ' Put the sequence number into a global variable
        '----------------------------------------
        SequenceNum = pre_sequence
        '----------------------------------------
        ' Start the application input and output
        '----------------------------------------
        ret = LoggerStartOperation(g_appid, status)
        '----------------------------------------
        ' Get error string
        '----------------------------------------
        LoggerGetErrorString(ret, error_string)
        '----------------------------------------
        ' Display error code and message
        '----------------------------------------
        textBox_ReturnNum.Text = String.Format("LoggerStartOperation = {0} : {1} {2}status = {3}", ret, error_string, vbCrLf, status)
    End Sub

    '================================================================================
    ' It is the process when the LoggerGetTotalSamplingCount button is clicked
    ' Get the total number of samples
    '================================================================================
    Private Sub button_LoggerGetTotalSamplingCount_Click(sender As Object, e As EventArgs) Handles button_LoggerGetTotalSamplingCount.Click
        Dim ret As Integer                                ' For return code
        Dim error_string As New StringBuilder("", 256)    ' Error code string
        Dim sampling_count As UInteger = 0                ' For total sampling count storage

        '----------------------------------------
        ' Get total sampling count
        '----------------------------------------
        ret = LoggerGetTotalSamplingCount(g_appid, sampling_count)
        '----------------------------------------
        ' Get error string
        '----------------------------------------
        LoggerGetErrorString(ret, error_string)
        '----------------------------------------
        ' Display error code and message
        '----------------------------------------
        textBox_ReturnNum.Text = String.Format("LoggerGetTotalSamplingCount = {0} : {1} ", ret, error_string)
        '----------------------------------------
        ' If the total sampling count acquisition function completes successfully
        '----------------------------------------
        If ret = 0 Then
            '----------------------------------------
            ' Update the toal sampling count
            '----------------------------------------
            textBox_TotalSamplingCount.Text = sampling_count.ToString()
        End If
    End Sub

    '================================================================================
    ' It is the process when the LoggerGetStoredSamplingCount button is clicked
    ' Get the number of samples
    '================================================================================
    Private Sub button_LoggerGetStoredSamplingCount_Click(sender As Object, e As EventArgs) Handles button_LoggerGetStoredSamplingCount.Click
        Dim ret As Integer                                ' For return code
        Dim error_string As New StringBuilder("", 256)    ' Error code string
        Dim stored_sampling_count As UInteger = 0         ' For sampling count storage

        '----------------------------------------
        ' Get sampling count
        '----------------------------------------
        ret = LoggerGetStoredSamplingCount(g_appid, stored_sampling_count)
        '----------------------------------------
        ' Get error string
        '----------------------------------------
        LoggerGetErrorString(ret, error_string)
        '----------------------------------------
        ' Display error code and message
        '----------------------------------------
        textBox_ReturnNum.Text = String.Format("LoggerGetStoredSamplingCount = {0} : {1} ", ret, error_string)
        '----------------------------------------
        ' If the specified sampling count acquisition function completes successfully
        '----------------------------------------
        If ret = 0 Then
            '----------------------------------------
            ' Update the sampling count
            '----------------------------------------
            textBox_StoredSamplingCount.Text = stored_sampling_count.ToString()
        End If
    End Sub

    '================================================================================
    ' It is the process when the LoggerGetApplicationStatus button is clicked
    ' Get the device status
    '================================================================================
    Private Sub button_LoggerGetApplicationStatus_Click(sender As Object, e As EventArgs) Handles button_LoggerGetApplicationStatus.Click
        Dim status_string As String = ""                  ' Status string
        Dim error_string As New StringBuilder("", 256)    ' Error code string
        Dim ret As Integer                                ' For return code
        Dim status As UInteger = LOGGER_STATUS_STOP       ' For status storage

        '----------------------------------------
        ' Get the device status
        '----------------------------------------
        ret = LoggerGetApplicationStatus(g_appid, status)
        '----------------------------------------
        ' Get error string
        '----------------------------------------
        LoggerGetErrorString(ret, error_string)
        '----------------------------------------
        ' Display error code and message
        '----------------------------------------
        textBox_ReturnNum.Text = String.Format("LoggerGetApplicationStatus = {0} : {1}", ret, error_string)
        '----------------------------------------
        ' If the status acquisition function is completed successfully
        '----------------------------------------
        If ret = 0 Then
            '----------------------------------------
            ' Get status string
            '----------------------------------------
            Select Case status
                Case CType(LOGGER_STATUS_STOP, UInteger)
                    status_string = "Stop"
                Case CType(LOGGER_STATUS_START_TRG, UInteger)
                    status_string = "Wait the start trigger"
                Case CType(LOGGER_STATUS_BUSY, UInteger)
                    status_string = "Operating"
                Case Else
                    status_string = "Unknown status"
            End Select
            '----------------------------------------
            ' Display the status
            '----------------------------------------
            textBox_Status.Text = String.Format("{0} ({1})", status, status_string)
        End If
    End Sub

    '================================================================================
    ' It is the process when the Logging Stop button is clicked
    ' Stop the application input and output
    '================================================================================
    Private Sub button_LoggerStopOperation_Click(sender As Object, e As EventArgs) Handles button_LoggerStopOperation.Click
        Dim ret As Integer                                ' For return code
        Dim error_string As New StringBuilder("", 256)    ' Error code string
        Dim sampling_times As UInteger                    ' For storing the specified sampling count
        Dim sampling_data() As Single                     ' For storing sampling data
        Dim i As Long                                     ' For loop counting
        Dim text_string As String = ""                    ' For updating textbox
        Dim fp As StreamWriter                            ' File pointer
		Dim j As Long                                     ' For loop counting

        '----------------------------------------
        ' Get a fixed pointer to the event notification delegate
        '----------------------------------------
        pfunc = Marshal.GetFunctionPointerForDelegate(pdelegate_func)
        '----------------------------------------
        ' Stop the application input and output
        '----------------------------------------
        ret = LoggerStopOperation(g_appid)
        If Not ret = 0 Then
            '----------------------------------------
            ' Get error string
            '----------------------------------------
            LoggerGetErrorString(ret, error_string)
            '----------------------------------------
            ' Display error code and message
            '----------------------------------------
            textBox_ReturnNum.Text = String.Format("LoggerStopOperation = {0} : {1} ", ret, error_string)
            Exit Sub
        End If
        '----------------------------------------
        ' Get the sampling count
        '----------------------------------------
        ret = LoggerGetStoredSamplingCount(g_appid, sampling_times)
        If Not ret = 0 Then
            '----------------------------------------
            ' Get error string
            '----------------------------------------
            LoggerGetErrorString(ret, error_string)
            '----------------------------------------
            ' Display error code and message
            '----------------------------------------
            textBox_ReturnNum.Text = String.Format("LoggerGetStoredSamplingCount = {0} : {1} ", ret, error_string)
            Exit Sub
        End If
        '----------------------------------------
        ' No sampling data
        '----------------------------------------
        If sampling_times <= 0 Then
            Exit Sub
        End If
        '----------------------------------------
        ' For storing data for a specified number of samplings
        '----------------------------------------
        Try
            sampling_data = New Single(sampling_times * SequenceNum - 1) {}
        Catch ex As Exception
            textBox_ReturnNum.Text = "Device operation termination event processing: Failed to allocate array for data storage"
            Exit Sub
        End Try
        '----------------------------------------
        ' Get sampling data
        '----------------------------------------
        ret = LoggerGetSamplingData(g_appid, sampling_times, sampling_data)
        If Not ret = 0 Then
            '----------------------------------------
            ' Get error string
            '----------------------------------------
            LoggerGetErrorString(ret, error_string)
            '----------------------------------------
            ' Display error code and message
            '----------------------------------------
            textBox_ReturnNum.Text = String.Format("LoggerGetSamplingData = {0} : {1} ", ret, error_string)
            '----------------------------------------
            ' Free the array used for data storage
            '----------------------------------------
            sampling_data = Nothing
            Exit Sub
        End If
        '----------------------------------------
        ' Open file
        '----------------------------------------
        Try
            fp = File.AppendText(g_file_name)
        Catch ex As Exception
            textBox_ReturnNum.Text = "Output Acquired Data File：File.AppendText = file open error."
            Exit Sub
        End Try
        '----------------------------------------
        ' Repeat processing until the specified number of samples is reached
        '----------------------------------------
        For i = 0 To sampling_times - 1
            '----------------------------------------
            ' Clear the display string storage variable
            '----------------------------------------
            text_string = ""
            '----------------------------------------
            ' Generate a string to display
            '----------------------------------------
            text_string += String.Format("{0,5},  ", g_samplingdata)
            g_samplingdata += 1
            '----------------------------------------
            ' Add sampling data (Repeat the process for the specified number of channels)
            '----------------------------------------
            For j = 0 To SequenceNum - 2
                text_string += String.Format(" {0,10:F5}, ", sampling_data(i * SequenceNum + j))
            Next
            text_string += String.Format(" {0,10:F5}" & vbCrLf, sampling_data(i * SequenceNum + j))
            '----------------------------------------
            ' Data writing
            '----------------------------------------
            Try
                fp.Write(text_string)
            Catch ex As Exception
                textBox_ReturnNum.Text = "Output Acquired Data Files：fp.Write = file write error."
                fp.Close()
                sampling_data = Nothing
                Exit Sub
            End Try
        Next
        fp.Close()
        '----------------------------------------
        ' Free the array used for data storage
        '----------------------------------------
        sampling_data = Nothing
        '----------------------------------------
        ' Display of collection stop completion message
        '----------------------------------------
        textBox_ReturnNum.Text = "LoggerStopOperation：Successful completion"
    End Sub

    '================================================================================
    ' It is the process when the C-LOGGER Exit button is clicked
    ' Stop the app and disable access
    '================================================================================
    Private Sub button_LoggerCloseApplication_Click(sender As Object, e As EventArgs) Handles button_LoggerCloseApplication.Click
        Dim status As UInteger = 0                        ' For status storage
        Dim ret As Integer                                ' For return code
        Dim error_string As New StringBuilder("", 256)    ' Error code string
        Dim status_string As String                       ' Status string

        '----------------------------------------
        ' Close the file(Considering that C-LOGGER may have exited, do not check the result)
        '----------------------------------------
        ret = LoggerGraphWindowOperation(g_appid, CType(LOGGER_PARAM_GRAPH_CLOSE, UShort), CType(LOGGER_PARAM_FILE, UShort), 0)
        '----------------------------------------
        ' Stop the application and disable access
        '----------------------------------------
        ret = LoggerCloseApplication(g_appid, status)
        '----------------------------------------
        ' Get error string
        '----------------------------------------
        LoggerGetErrorString(ret, error_string)
        If Not ret = 0 Then
            '----------------------------------------
            ' Display error code and message
            '----------------------------------------
            textBox_ReturnNum.Text = String.Format("LoggerCloseApplication = {0} : {1} ", ret, error_string)
            Exit Sub
        End If
        '----------------------------------------
        ' Get status string
        '----------------------------------------
        Select Case status
            Case CType(LOGGER_STATUS_SUCCESS, UInteger)
                status_string = "Successful completion"
            Case CType(LOGGER_STATUS_FAILURE, UInteger)
                status_string = "C-LOGGER exit error"
            Case Else
                status_string = "Unknown status"
        End Select
        '----------------------------------------
        ' Display error code and message
        '----------------------------------------
        textBox_ReturnNum.Text = String.Format("LoggerCloseApplication = {0} : {1} {2}status = {3} : {4}", ret, error_string, vbCrLf, status, status_string)
    End Sub

    '================================================================================
    ' It is the process when the Close button is clicked
    ' Exit the application
    '================================================================================
    Private Sub button_Close_Click(sender As Object, e As EventArgs) Handles button_Close.Click
        Dim status As UInteger = 0                        ' For status storage

        '----------------------------------------
        ' Close the file(Considering that C-LOGGER may have exited, do not check the result)
        '----------------------------------------
        LoggerGraphWindowOperation(g_appid, CType(LOGGER_PARAM_GRAPH_CLOSE, UShort), CType(LOGGER_PARAM_FILE, UShort), 0)
        '----------------------------------------
        ' Stop the application and disable access
        '----------------------------------------
        LoggerCloseApplication(g_appid, status)
        '----------------------------------------
        ' Releasing a GCHandle
        '----------------------------------------
        If (gCh.IsAllocated = True) Then
            gCh.Free()
        End If
        '----------------------------------------
        ' Exit the dialog
        '----------------------------------------
        Me.Close()
    End Sub

    '================================================================================
    ' Callback routine
    '================================================================================
    Protected Sub CallBackProc(ByVal Id As Short, ByVal [Event] As UInteger, ByVal wParam As Integer, ByVal lParam As Integer, ByVal Param As IntPtr)
        Dim ret As Integer                                ' For return code
        Dim sampling_times As UInteger                    ' For storing the specified sampling count
        Dim error_string As New StringBuilder("", 256)    ' Error code string
        Dim sampling_data() As Single                     ' For storing sampling data
        Dim i As Long                                     ' For loop counting
        Dim text_string As String = ""                    ' For updating textbox
        Dim fp As StreamWriter                            ' File pointer
        Dim j As Long                                     ' ループカウント用

        '----------------------------------------
        ' Specified Number Storage Event
        '----------------------------------------
        If [Event] = CLng(LOGGER_PARAM_EVENT_DATANUM) Then
            '----------------------------------------
            ' Get the sampling count
            '----------------------------------------
            ret = LoggerGetStoredSamplingCount(g_appid, sampling_times)
            If Not ret = 0 Then
                '----------------------------------------
                ' Get error string
                '----------------------------------------
                LoggerGetErrorString(ret, error_string)
                '----------------------------------------
                ' Display error code and message
                '----------------------------------------
                Me.Invoke(New Action(Sub() textBox_ReturnNum.Text = String.Format("LoggerGetStoredSamplingCount = {0} : {1} ", ret, error_string)))
                Exit Sub
            End If
            '----------------------------------------
            ' For storing data for the specified number of samples
            '----------------------------------------
            Try
                sampling_data = New Single(sampling_times * SequenceNum - 1) {}
            Catch ex As Exception
                Me.Invoke(New Action(Sub() textBox_ReturnNum.Text = "Device operation termination event processing: Failed to allocate array for data storage"))
                Exit Sub
            End Try
            '----------------------------------------
            ' Get sampling data
            '----------------------------------------
            ret = LoggerGetSamplingData(g_appid, sampling_times, sampling_data)
            If Not ret = 0 Then
                '----------------------------------------
                ' Get error string
                '----------------------------------------
                LoggerGetErrorString(ret, error_string)
                '----------------------------------------
                ' Display error code and message
                '----------------------------------------
                Me.Invoke(New Action(Sub() textBox_ReturnNum.Text = String.Format("LoggerGetSamplingData = {0} : {1} ", ret, error_string)))
                '----------------------------------------
                ' Free the array used for data storage
                '----------------------------------------
                sampling_data = Nothing
                Exit Sub
            End If
            '----------------------------------------
            ' Open file
            '----------------------------------------
            Try
                fp = File.AppendText(g_file_name)
            Catch ex As Exception
                Me.Invoke(New Action(Sub() textBox_ReturnNum.Text = "Output Acquired Data Files：File.AppendText = file open error."))
                Exit Sub
            End Try
            '----------------------------------------
            ' Repeat processing until the specified number of samples is reached
            '----------------------------------------
            For i = 0 To sampling_times - 1
                '----------------------------------------
                ' Clear the display string storage variable
                '----------------------------------------
                text_string = ""
                '----------------------------------------
                ' Generate a string to display
                '----------------------------------------
                text_string += String.Format("{0,5},  ", g_samplingdata)
                g_samplingdata += 1
                '----------------------------------------
                ' Add sampling data (Repeat the process for the specified number of channels)
                '----------------------------------------
                For j = 0 To SequenceNum - 2
                    text_string += String.Format(" {0,10:F5}, ", sampling_data(i * SequenceNum + j))
                Next
                text_string += String.Format(" {0,10:F5}" & vbCrLf, sampling_data(i * SequenceNum + j))
                '----------------------------------------
                ' Data writing
                '----------------------------------------
                Try
                    fp.Write(text_string)
                Catch ex As Exception
                    Me.Invoke(New Action(Sub() textBox_ReturnNum.Text = "Output Acquired Data Files：fp.Write = file write error."))
                    fp.Close()
                    '----------------------------------------
                    ' Free the array used for data storage
                    '----------------------------------------
                    sampling_data = Nothing
                    Exit Sub
                End Try
            Next

            fp.Close()
            '----------------------------------------
            ' Free the array used for data storage
            '----------------------------------------
            sampling_data = Nothing
            '----------------------------------------
            ' Specified Number End Event
            '----------------------------------------
        ElseIf [Event] = CLng(LOGGER_PARAM_EVENT_END) Then
            '----------------------------------------
            ' Get the sampling count
            '----------------------------------------
            ret = LoggerGetStoredSamplingCount(g_appid, sampling_times)
            If Not ret = 0 Then
                '----------------------------------------
                ' Get error string
                '----------------------------------------
                LoggerGetErrorString(ret, error_string)
                '----------------------------------------
                ' Display error code and message
                '----------------------------------------
                Me.Invoke(New Action(Sub() textBox_ReturnNum.Text = String.Format("LoggerGetStoredSamplingCount = {0} : {1} ", ret, error_string)))
                Exit Sub
            End If
            '----------------------------------------
            ' For storing data for the specified number of samples
            '----------------------------------------
            Try
                sampling_data = New Single(sampling_times * SequenceNum - 1) {}
            Catch ex As Exception
                Me.Invoke(New Action(Sub() textBox_ReturnNum.Text = "Device operation termination event processing: Failed to allocate array for data storage"))
                Exit Sub
            End Try
            '----------------------------------------
            ' Get sampling data
            '----------------------------------------
            ret = LoggerGetSamplingData(g_appid, sampling_times, sampling_data)
            If Not ret = 0 Then
                '----------------------------------------
                ' Get error string
                '----------------------------------------
                LoggerGetErrorString(ret, error_string)
                '----------------------------------------
                ' Display error code and message
                '----------------------------------------
                Me.Invoke(New Action(Sub() textBox_ReturnNum.Text = String.Format("LoggerGetSamplingData = {0} : {1} ", ret, error_string)))

                '----------------------------------------
                ' Free the array used for data storage
                '----------------------------------------
                sampling_data = Nothing
                Exit Sub
            End If
            '----------------------------------------
            ' Open file
            '----------------------------------------
            Try
                fp = File.AppendText(g_file_name)
            Catch ex As Exception
                Me.Invoke(New Action(Sub() textBox_ReturnNum.Text = "Output Acquired Data Files：File.AppendText = file open error."))
                Exit Sub
            End Try
            '----------------------------------------
            ' Repeat processing until the specified number of samples is reached
            '----------------------------------------
            For i = 0 To sampling_times - 1
                '----------------------------------------
                ' Clear the display string storage variable
                '----------------------------------------
                text_string = ""
                '----------------------------------------
                ' Generate a string to display
                '----------------------------------------
                text_string += String.Format("{0,5},  ", g_samplingdata)
                g_samplingdata += 1
                '----------------------------------------
                ' Add sampling data (Repeat the process for the specified number of channels)
                '----------------------------------------
                For j = 0 To SequenceNum - 2
                    text_string += String.Format(" {0,10:F5}, ", sampling_data(i * SequenceNum + j))
                Next
                text_string += String.Format(" {0,10:F5}" & vbCrLf, sampling_data(i * SequenceNum + j))
                '----------------------------------------
                ' Data writing
                '----------------------------------------
                Try
                    fp.Write(text_string)
                Catch ex As Exception
                    Me.Invoke(New Action(Sub() textBox_ReturnNum.Text = "Output Acquired Data Files：fp.Write = file write error."))
                    fp.Close()
                    '----------------------------------------
                    ' Free the array used for data storage
                    '----------------------------------------
                    sampling_data = Nothing
                    Exit Sub
                End Try
            Next
            fp.Close()
            '----------------------------------------
            ' Free the array used for data storage
            '----------------------------------------
            sampling_data = Nothing
        End If
        Exit Sub
    End Sub

End Class
