﻿' High-performance Counter Sample
Imports VB = Microsoft.VisualBasic
Imports System.Text

Public Class Form1
    'Return value of function
    'ID
    Public Shared Id As Short
    Public Shared ChannelNum As Short
    Public Shared hMainWnd As IntPtr
    Const CHANNEL_NUM As Short = 4

    Dim CountMatch(CHANNEL_NUM) As UInteger
    Dim gMode As New Mode()
    Dim g_Event As New Events()
    Dim gNotify As New Notify()
    Dim txt_Count(CHANNEL_NUM) As TextBox
    Dim txt_Status(CHANNEL_NUM) As TextBox

    '-----------------------------------
    ' Dialog initialization
    '-----------------------------------
    Private Sub frmCounter_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim i As Short

        Me.Left = (Screen.PrimaryScreen.Bounds.Width - Me.Width) / 2
        Me.Top = (Screen.PrimaryScreen.Bounds.Height - Me.Height) / 2

        '-----------------------------------
        ' Control array settings
        '-----------------------------------
        '-----------------
        ' Count value control
        '-----------------
        txt_Count(0) = txtCountValue0
        txt_Count(1) = txtCountValue1
        txt_Count(2) = txtCountValue2
        txt_Count(3) = txtCountValue3
        '-----------------
        ' Count status control
        '-----------------
        txt_Status(0) = txtCountStatus0
        txt_Status(1) = txtCountStatus1
        txt_Status(2) = txtCountStatus2
        txt_Status(3) = txtCountStatus3
        '-----------------------------------
        ' Initialize dialog display
        '-----------------------------------
        txtDeviceName.Text = "CNT000"
        '-----------------------------------
        ' For each channel
        '-----------------------------------
        For i = 0 To CHANNEL_NUM - 1
            '-----------------
            ' Count value control
            '-----------------
            txt_Count(i).Text = ""
            '-----------------
            ' Count status control
            '-----------------
            txt_Status(i).Text = ""
        Next i
        '-----------------------------------
        ' Initializing Parameters
        '-----------------------------------
        ChannelNum = CHANNEL_NUM
        '-----------------------------------
        ' Copy window's handle
        '-----------------------------------
        hMainWnd = Me.Handle

    End Sub

    '---------------------------------------------
    ' CntInit()
    '---------------------------------------------
    Private Sub btnCntInit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCntInit.Click
        Dim buf As New String("", 100)
        Dim error_string As New StringBuilder("", 256)
        Dim ret As Integer
        Dim i As Short

        '------------------------------
        ' Initialization
        '------------------------------
        ret = CntInit(txtDeviceName.Text, Id)
        CntGetErrorString(ret, error_string)
        txtRet.Text = "CntInit ret = " & ret & ": " & error_string.ToString()
        
        If (ret <> CNT_ERR_SUCCESS) Then
            Exit Sub
        End If

        '------------------------------
        ' Get number of channels
        '------------------------------
        Call CntGetMaxChannels(Id, ChannelNum)

        '------------------------------
        ' If the sample control count is exceeded, 
        ' the total channel count is corrected to the control count.
        '------------------------------
        if (ChannelNum > CHANNEL_NUM) Then
            ChannelNum = CHANNEL_NUM
        End If

        '------------------------------
        ' Toggles the count value and status display according to the total number of channels.
        '------------------------------
        For i = 0 To CHANNEL_NUM - 1
            '------------------------------
            ' Disables the display when the number of loops exceeds the total number of channels.
            '------------------------------
            if (i >= ChannelNum) Then
                txt_Count(i).Enabled = False
                txt_Status(i).Enabled = False
            '------------------------------
            ' Enables the display when the number of loops is less than or equal to the total number of channels.
            '------------------------------
            Else
                txt_Count(i).Enabled = True
                txt_Status(i).Enabled = True
            End If
        Next i

    End Sub

    '---------------------------------------------
    ' Display Counter Mode Setting dialog
    '---------------------------------------------
    Private Sub btnCntMode_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCntMode.Click
        '------------------------------
        ' Display Counter Mode Setting dialog
        '------------------------------
        gMode.Show()
    End Sub

    '---------------------------------------------
    ' Display Notification Setting dialog
    '---------------------------------------------
    Private Sub btnCntNotify_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCntNotify.Click
        '------------------------------
        ' Display Notification Setting dialog
        '------------------------------
        gNotify.Show()
    End Sub

    '---------------------------------------------
    ' Display Event Setting dialog
    '---------------------------------------------
    Private Sub btnCntEvent_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCntEvent.Click
        '------------------------------
        ' Display Event Setting dialog
        '------------------------------
        g_Event.Show()
    End Sub

    '---------------------------------------------
    ' Start count
    '---------------------------------------------
    Private Sub btnCntStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCntStart.Click
        Dim error_string As New StringBuilder("", 256)
        Dim ret As Integer
        Dim ChNo(CHANNEL_NUM) As Short
        Dim i As Short
        '------------------------------
        ' Set parameters
        '------------------------------
        For i = 0 To ChannelNum - 1
            ChNo(i) = i
        Next i

        '------------------------------
        ' Start count
        '------------------------------
        ret = CntStartCount(Id, ChNo, ChannelNum)
        CntGetErrorString(ret, error_string)
        txtRet.Text = "CntStartCount ret = " & ret & ": " & error_string.ToString()

        If ret = 0 Then
            '------------------------------
            ' Consider a device that does not have a timer notification function,
            ' we use the window timer.
            ' Please switch and use, according to the use.
            '------------------------------
            '------------------------------
            ' Start Timer
            '------------------------------
            timer1.Start()
            '------------------------------
            ' When using the timer notification event of device,
            ' please use the following function.
            '------------------------------
            'CntNotifyTimer(Id, 100, Me.Handle.ToInt32)
        End If
    End Sub

    '---------------------------------------------
    ' Preset counter
    '---------------------------------------------
    Private Sub btnCntPreset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCntPreset.Click
        Dim error_string As New StringBuilder("", 256)
        Dim ret As Integer
        Dim ChNo(CHANNEL_NUM) As Short
        Dim PresetData(CHANNEL_NUM) As Integer
        Dim i As Short

        '------------------------------
        ' Set preset value
        '------------------------------
        For i = 0 To ChannelNum - 1
            ChNo(i) = i
            PresetData(i) = i * 100
        Next i

        '------------------------------
        ' Set preset
        '------------------------------
        ret = CntPreset(Id, ChNo, ChannelNum, PresetData)
        CntGetErrorString(ret, error_string)
        txtRet.Text = "CntPreset ret = " & ret & ": " & error_string.ToString()
    End Sub

    '---------------------------------------------
    ' Reset counter
    '---------------------------------------------
    Private Sub btnCntReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCntReset.Click
        Dim error_string As New StringBuilder("", 256)
        Dim ret As Integer
        Dim ChNo(CHANNEL_NUM) As Short
        Dim i As Short

        '------------------------------
        ' Set parameters
        '------------------------------
        For i = 0 To ChannelNum - 1
            ChNo(i) = i
        Next i

        '------------------------------
        ' Reset counter
        '------------------------------
        ret = CntZeroClearCount(Id, ChNo, ChannelNum)
        CntGetErrorString(ret, error_string)
        txtRet.Text = "CntZeroClearCount ret = " & ret & ": " & error_string.ToString()
    End Sub

    '---------------------------------------------
    ' Stop count
    '---------------------------------------------
    Private Sub btnCntStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCntStop.Click
        Dim error_string As New StringBuilder("", 256)
        Dim ret As Integer
        Dim ChNo(CHANNEL_NUM) As Short
        Dim i As Short

        '------------------------------
        ' Set parameters
        '------------------------------
        For i = 0 To ChannelNum - 1
            ChNo(i) = i
        Next i

        '------------------------------
        ' Stop counter
        '------------------------------
        ret = CntStopCount(Id, ChNo, ChannelNum)
        CntGetErrorString(ret, error_string)
        txtRet.Text = "CntStopCount ret = " & ret & ": " & error_string.ToString()

        '------------------------------
        ' Consider a device that does not have a timer notification function,
        ' we use the window timer.
        ' Please switch and use, according to the use.
        '------------------------------
        '------------------------------
        ' Stop timer
        '------------------------------
        timer1.Stop()
        '------------------------------
        ' When using the timer notification event of device,
        ' please use the following function.
        '------------------------------
        'CntStopNotifyTimer(Id)

    End Sub

    '---------------------------------------------
    ' CntExit()
    '---------------------------------------------
    Private Sub btnCntExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCntExit.Click
        Dim error_string As New StringBuilder("", 256)
        Dim ret As Integer

        '------------------------------
        ' Consider a device that does not have a timer notification function,
        ' we use the window timer.
        ' Please switch and use, according to the use.
        '------------------------------
        '------------------------------
        ' Stop timer
        '------------------------------
        timer1.Stop()
        '------------------------------
        ' When using the timer notification event of device,
        ' please use the following function.
        '------------------------------
        'CntStopNotifyTimer(Id)

        '------------------------------
        ' Counter termination processing
        '------------------------------
        ret = CntExit(Id)
        CntGetErrorString(ret, error_string)
        txtRet.Text = "CntExit ret = " & ret & ": " & error_string.ToString()
    End Sub

    '---------------------------------------------
    ' Exit sample program
    '---------------------------------------------
    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        Dim ret As Integer

        '------------------------------
        ' Consider a device that does not have a timer notification function,
        ' we use the window timer.
        ' Please switch and use, according to the use.
        '------------------------------
        '------------------------------
        ' Stop timer
        '------------------------------
        timer1.Stop()
        '------------------------------
        ' When using the timer notification event of device,
        ' please use the following function.
        '------------------------------
        'CntStopNotifyTimer(Id)

        '------------------------------
        ' Counter termination processing
        '------------------------------
        ret = CntExit(Id)
        End
    End Sub

    '------------------------------
    ' Consider a device that does not have a timer notification function,
    ' we use the window timer.
    ' When using the timer notification function, please comment out the following method.
    '------------------------------
    Private Sub timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles timer1.Tick

        Dim ChNo(CHANNEL_NUM) As Short
        Dim CntData(CHANNEL_NUM) As Integer
        Dim StatusData(CHANNEL_NUM) As Integer
        Dim i As Short
        Dim ret As Integer
        Dim error_string As New StringBuilder("", 256)

        '------------------------------
        ' Set parameter
        '------------------------------
        For i = 0 To ChannelNum - 1
            ChNo(i) = i
            CntData(i) = 0
            StatusData(i) = 0
        Next i
        '------------------------------
        ' Get count value
        '------------------------------
        ret = CntReadCount(Id, ChNo, ChannelNum, CntData)
        If ret <> 0 Then
            CntGetErrorString(ret, error_string)
            txtRet.Text = String.Format("CntReadCnt ret = {0:D}: " & error_string.ToString(), ret)
            '------------------------------
            ' Stop timer
            '------------------------------
            timer1.Stop()
        End If
        '------------------------------
        ' Get count status
        '------------------------------
        For i = 0 To ChannelNum - 1
            ret = CntReadStatusEx(Id, i, StatusData(i))
            If ret <> 0 Then
                CntGetErrorString(ret, error_string)
                txtRet.Text = String.Format("CntReadStatus ret = {0:D}: " & error_string.ToString(), ret)
                '------------------------------
                ' Stop timer
                '------------------------------
                timer1.Stop()
            End If
        Next i

        '------------------------------
        ' Display data
        '------------------------------
        For i = 0 To ChannelNum - 1
            ' In order to display the count data to unsigned, convert it once through hexadecimal characters
            txt_Count(i).Text = String.Format("{0:D}", Convert.ToUInt32(Hex(CntData(i)), 16))
            txt_Status(i).Text = String.Format("{0:X8}H", StatusData(i))
        Next i

    End Sub

    '---------------------------------------------
    ' Counter event notification processing
    '---------------------------------------------
    Protected Overrides Sub WndProc(ByRef m As Message)

        Dim CntData(CHANNEL_NUM) As Integer
        Dim StatusData(CHANNEL_NUM) As Integer
        Dim error_string As New StringBuilder("", 256)

        Select Case m.Msg

            Case CNTM_COUNTUP_CH0 ' Count match: 0CH
                CountMatch(0) = CountMatch(0) + 1
                If HiLoWord(m.WParam.ToInt32, 1) = 1 Then
                    lblNotify.Text = String.Format("Count Match! Channel No.: 0, UP, " & vbCrLf & "Count: {0:X8}(Hex) Matched: {1:D}times", Hex(Val(m.LParam.ToString)), CountMatch(0))
                Else
                    lblNotify.Text = String.Format("Count Match! Channel No.: 0, DOWN, " & vbCrLf & "Count: {0:X8}(Hex) Matched: {1:D}times", Hex(Val(m.LParam.ToString)), CountMatch(0))
                End If

            Case CNTM_COUNTUP_CH1 ' Count match: 1CH
                CountMatch(1) = CountMatch(1) + 1
                If HiLoWord(m.WParam.ToInt32, 1) = 1 Then
                    lblNotify.Text = String.Format("Count Match! Channel No.: 1, UP, " & vbCrLf & "Count: {0:X8}(Hex) Matched: {1:D}times", Hex(Val(m.LParam.ToString)), CountMatch(1))
                Else
                    lblNotify.Text = String.Format("Count Match! Channel No.: 1, DOWN, " & vbCrLf & "Count: {0:X8}(Hex) Matched: {1:D}times", Hex(Val(m.LParam.ToString)), CountMatch(1))
                End If

            Case CNTM_COUNTUP_CH2 ' Count match: 2CH
                CountMatch(2) = CountMatch(2) + 1
                If HiLoWord(m.WParam.ToInt32, 1) = 1 Then
                    lblNotify.Text = String.Format("Count Match! Channel No.: 2, UP, " & vbCrLf & "Count: {0:X8}(Hex) Matched: {1:D}times", Hex(Val(m.LParam.ToString)), CountMatch(2))
                Else
                    lblNotify.Text = String.Format("Count Match! Channel No.: 2, DOWN, " & vbCrLf & "Count: {0:X8}(Hex) Matched: {1:D}times", Hex(Val(m.LParam.ToString)), CountMatch(2))
                End If

            Case CNTM_COUNTUP_CH3 ' Count match: 3CH
                CountMatch(3) = CountMatch(3) + 1
                If HiLoWord(m.WParam.ToInt32, 1) = 1 Then
                    lblNotify.Text = String.Format("Count Match! Channel No.: 3, UP, " & vbCrLf & "Count: {0:X8}(Hex) Matched: {1:D}times", Hex(Val(m.LParam.ToString)), CountMatch(3))
                Else
                    lblNotify.Text = String.Format("Count Match! Channel No.: 3, DOWN, " & vbCrLf & "Count: {0:X8}(Hex) Matched: {1:D}times", Hex(Val(m.LParam.ToString)), CountMatch(3))
                End If

            Case CNTM_COUNTER_ERROR ' Counter error
                Select Case HiLoWord(m.LParam.ToInt32, 0)
                    Case CNT_AI_ERROR  ' Abnormal input
                        lblNotify.Text = String.Format("Abnormal input error! Channel No.: {0:D}", HiLoWord(m.WParam.ToInt32, 1))
                    Case CNT_FLT_ERROR ' Filter
                        lblNotify.Text = String.Format("Filter error! Channel No.: {0:D}", HiLoWord(m.WParam.ToInt32, 1))
                    Case CNT_ALM_ERROR ' Alarm
                        lblNotify.Text = String.Format("Alarm error! Channel No.: {0:D}", HiLoWord(m.WParam.ToInt32, 1))
                End Select
            Case CNTM_CARRY_BORROW ' Carry/Borrow
                Select Case HiLoWord(m.LParam.ToInt32, 0)
                    Case CNT_CB_CARRY  ' Carry
                        lblNotify.Text = String.Format("Carry! Channel No.: {0:D}", HiLoWord(m.WParam.ToInt32, 1))
                    Case CNT_CB_BORROW ' Borrow
                        lblNotify.Text = String.Format("Borrow! Channel No.: {0:D}", HiLoWord(m.WParam.ToInt32, 1))
                End Select

                '------------------------------
                ' When using the timer notification event of device,
                ' please use the following message.
                '------------------------------
                'Case CNTM_TIMER    ' Timer notification
                '    Dim ChNo(CHANNEL_NUM) As Short
                '    Dim i As Short
                '    Dim ret As Integer
                '    '------------------------------
                '    ' Set parameters
                '    '------------------------------
                '    For i = 0 To ChannelNum - 1
                '        ChNo(i) = i
                '        CntData(i) = 0
                '        StatusData(i) = 0
                '    Next i
                '    '------------------------------
                '    ' Get count value
                '    '------------------------------
                '    ret = CntReadCount(Id, ChNo, ChannelNum, CntData)
                '    If ret <> 0 Then
                '        CntGetErrorString(ret, error_string)
                '        txtRet.Text = String.Format("CntReadCnt ret = {0:D}: " & error_string.ToString(), ret)
                '        CntStopNotifyTimer(Id)
                '    End If
                '    '------------------------------
                '    ' Get count status
                '    '------------------------------
                '    For i = 0 To ChannelNum - 1
                '        ret = CntReadStatusEx(Id, i, StatusData(i))
                '        If ret <> 0 Then
                '            CntGetErrorString(ret, error_string)
                '            txtRet.Text = String.Format("CntReadStatus ret = {0:D}: " & error_string.ToString(), ret)
                '            CntStopNotifyTimer(Id)
                '        End If
                '    Next i

                '    '------------------------------
                '    ' Display data
                '    '------------------------------
                '    For i = 0 To ChannelNum - 1
                '        ' In order to display the count data to unsigned, convert it once through hexadecimal characters
                '        txt_Count(i).Text = String.Format("{0:D}", Convert.ToUInt32(Hex(CntData(i)), 16))
                '        txt_Status(i).Text = String.Format("{0:X8}H", StatusData(i))
                '    Next i
        End Select
        MyBase.WndProc(m)
    End Sub

    '---------------------------------------------------------
    ' Subroutine: Get HIWORD, LOWORD
    '---------------------------------------------------------
    Function HiLoWord(ByRef Number As Integer, ByRef HiLo As Short) As Integer

        Dim Hi As Integer
        Dim Lo As Integer
        Dim StrData As String
        Dim i As Short

        StrData = Hex(Number)
        If Len(StrData) < 8 Then
            For i = 1 To 8 - Len(StrData)
                StrData = "0" & StrData
            Next i
        End If

        Lo = Val("&h" & VB.Right(StrData, 4))
        Hi = Val("&h" & VB.Left(StrData, 4))
        If HiLo = 0 Then
            HiLoWord = Lo
        ElseIf HiLo = 1 Then
            HiLoWord = Hi
        End If

        Return HiLoWord
    End Function
End Class
