'電話を掛けると無線機で取るやつ。

Public Class Form1
    '着信なのか発信なのかのフラグ。着信でTrue
    Dim callflag As Boolean

    '起動時の処理
    Private Sub Form1_Shown(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Shown
        Button1.Enabled = False
        SerialPort1.NewLine = vbCr
        SerialPortOpen()
        Timer1.Stop()
    End Sub

    'オンフック、オフフックボタンを押したときの処理
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If Button1.Text = "ON" Then
            If callflag = True Then
                SerialPort1.WriteLine("ATA")    '着信
            Else
                SerialPort1.WriteLine("ATD" & TextBox1.Text & ";")  '発信
            End If
            Button1.Text = "OFF"
        Else
            SerialPort1.WriteLine("ATH")    '切断
            callflag = False
            Button1.Text = "ON"
            Timer1.Enabled = False
        End If
    End Sub


    '着信があった場合の処理
    '電話番号は通知してもしなくてもOK
    Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        If SerialPort1.ReadLine = "CALLING" Then
            Control.CheckForIllegalCrossThreadCalls = False
            Label1.Text = "CALLING"
            Debug.Print(Timer1.Enabled & Now)
            callflag = True
            Timer1.Interval = 1000
            Timer1.Start()          '着信を5秒たっても"CALLING"がこなかったら相手が切断したと判断する
            'SerialPort1.RtsEnable = True    'バイブをイネーブルする。
            Debug.Print(Timer1.Enabled & Now)
        End If
    End Sub

    '着信を5秒たっても"CALLING"がこなかったら相手が切断したと判断する
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Debug.Print("TIMERTICK " & Now())
        Label1.Text = "CALLED"
        'Timer1.Enabled = False
    End Sub

    'COMポートを変更した場合の処理
    Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
        SerialPortOpen()
    End Sub

    'COMポートを開きます。
    Private Sub SerialPortOpen()
        If SerialPort1.IsOpen = True Then
            SerialPort1.Close()
        End If
        Try
            SerialPort1.PortName = TextBox2.Text
            SerialPort1.Open()
            Button1.Enabled = True
        Catch ex As Exception
            Button1.Enabled = False
        End Try
    End Sub

    '終了時にはCOMポートを閉じます。
    Private Sub Form1_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
        If SerialPort1.IsOpen = True Then
            SerialPort1.Close()
        End If
    End Sub



    Private Sub Form1_MouseDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDoubleClick
        Timer1.Enabled = True
    End Sub
End Class