Imports System.IO
Imports System.Text

'=========================================================================
'クラス名称：遠隔監視アプリケーションメインクラス
'機能      ：USBカメラプロバイダを利用して遠隔監視をおこなう
'備考      ：なし
'=========================================================================
Public Class frmMain
    Inherits System.Windows.Forms.Form

#Region " Windows フォーム デザイナで生成されたコード "

    Public Sub New()
        MyBase.New()

        ' この呼び出しは Windows フォーム デザイナで必要です。
        InitializeComponent()

        ' InitializeComponent() 呼び出しの後に初期化を追加します。

    End Sub

    ' Form は、コンポーネント一覧に後処理を実行するために dispose をオーバーライドします。
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    ' Windows フォーム デザイナで必要です。
    Private components As System.ComponentModel.IContainer

    ' メモ : 以下のプロシージャは、Windows フォーム デザイナで必要です。
    'Windows フォーム デザイナを使って変更してください。  
    ' コード エディタを使って変更しないでください。
    Friend WithEvents btnStart As System.Windows.Forms.Button
    Friend WithEvents btnStop As System.Windows.Forms.Button
    Friend WithEvents barThreshold As System.Windows.Forms.TrackBar
    Friend WithEvents txtLog As System.Windows.Forms.TextBox
    Friend WithEvents stsBar As System.Windows.Forms.StatusBar
    Friend WithEvents StatusBarPanel1 As System.Windows.Forms.StatusBarPanel
    Friend WithEvents btnClear As System.Windows.Forms.Button
    Friend WithEvents MenuItem1 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem2 As System.Windows.Forms.MenuItem
    Friend WithEvents MenuItem6 As System.Windows.Forms.MenuItem
    Friend WithEvents menuExit As System.Windows.Forms.MenuItem
    Friend WithEvents menuMailSetting As System.Windows.Forms.MenuItem
    Friend WithEvents menuPictureSave As System.Windows.Forms.MenuItem
    Friend WithEvents menuLogSave As System.Windows.Forms.MenuItem
    Friend WithEvents menuMain As System.Windows.Forms.MainMenu
    Friend WithEvents dlgSavePicture As System.Windows.Forms.SaveFileDialog
    Friend WithEvents dlgSaveLog As System.Windows.Forms.SaveFileDialog
    Friend WithEvents GroupBox1 As System.Windows.Forms.GroupBox
    Friend WithEvents GroupBox2 As System.Windows.Forms.GroupBox
    Friend WithEvents GroupBox3 As System.Windows.Forms.GroupBox
    Friend WithEvents MenuItem3 As System.Windows.Forms.MenuItem
    Friend WithEvents menuProviderSetting As System.Windows.Forms.MenuItem
    Friend WithEvents pctBox As System.Windows.Forms.PictureBox
    Friend WithEvents menuVersion As System.Windows.Forms.MenuItem
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Me.pctBox = New System.Windows.Forms.PictureBox
        Me.btnStart = New System.Windows.Forms.Button
        Me.btnStop = New System.Windows.Forms.Button
        Me.barThreshold = New System.Windows.Forms.TrackBar
        Me.txtLog = New System.Windows.Forms.TextBox
        Me.stsBar = New System.Windows.Forms.StatusBar
        Me.StatusBarPanel1 = New System.Windows.Forms.StatusBarPanel
        Me.btnClear = New System.Windows.Forms.Button
        Me.menuMain = New System.Windows.Forms.MainMenu(Me.components)
        Me.MenuItem1 = New System.Windows.Forms.MenuItem
        Me.menuPictureSave = New System.Windows.Forms.MenuItem
        Me.menuLogSave = New System.Windows.Forms.MenuItem
        Me.MenuItem6 = New System.Windows.Forms.MenuItem
        Me.menuExit = New System.Windows.Forms.MenuItem
        Me.MenuItem2 = New System.Windows.Forms.MenuItem
        Me.menuProviderSetting = New System.Windows.Forms.MenuItem
        Me.menuMailSetting = New System.Windows.Forms.MenuItem
        Me.MenuItem3 = New System.Windows.Forms.MenuItem
        Me.menuVersion = New System.Windows.Forms.MenuItem
        Me.dlgSavePicture = New System.Windows.Forms.SaveFileDialog
        Me.dlgSaveLog = New System.Windows.Forms.SaveFileDialog
        Me.GroupBox1 = New System.Windows.Forms.GroupBox
        Me.GroupBox2 = New System.Windows.Forms.GroupBox
        Me.GroupBox3 = New System.Windows.Forms.GroupBox
        CType(Me.pctBox, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.barThreshold, System.ComponentModel.ISupportInitialize).BeginInit()
        CType(Me.StatusBarPanel1, System.ComponentModel.ISupportInitialize).BeginInit()
        Me.GroupBox1.SuspendLayout()
        Me.GroupBox2.SuspendLayout()
        Me.GroupBox3.SuspendLayout()
        Me.SuspendLayout()
        '
        'pctBox
        '
        Me.pctBox.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
        Me.pctBox.Location = New System.Drawing.Point(16, 24)
        Me.pctBox.Name = "pctBox"
        Me.pctBox.Size = New System.Drawing.Size(320, 240)
        Me.pctBox.TabIndex = 1
        Me.pctBox.TabStop = False
        '
        'btnStart
        '
        Me.btnStart.Location = New System.Drawing.Point(384, 304)
        Me.btnStart.Name = "btnStart"
        Me.btnStart.Size = New System.Drawing.Size(88, 24)
        Me.btnStart.TabIndex = 3
        Me.btnStart.Text = "開始"
        '
        'btnStop
        '
        Me.btnStop.Location = New System.Drawing.Point(384, 344)
        Me.btnStop.Name = "btnStop"
        Me.btnStop.Size = New System.Drawing.Size(88, 24)
        Me.btnStop.TabIndex = 4
        Me.btnStop.Text = "終了"
        '
        'barThreshold
        '
        Me.barThreshold.Location = New System.Drawing.Point(16, 16)
        Me.barThreshold.Maximum = 30
        Me.barThreshold.Name = "barThreshold"
        Me.barThreshold.Size = New System.Drawing.Size(328, 42)
        Me.barThreshold.TabIndex = 6
        Me.barThreshold.Value = 10
        '
        'txtLog
        '
        Me.txtLog.Location = New System.Drawing.Point(16, 24)
        Me.txtLog.Multiline = True
        Me.txtLog.Name = "txtLog"
        Me.txtLog.ReadOnly = True
        Me.txtLog.ScrollBars = System.Windows.Forms.ScrollBars.Vertical
        Me.txtLog.Size = New System.Drawing.Size(208, 240)
        Me.txtLog.TabIndex = 7
        '
        'stsBar
        '
        Me.stsBar.Location = New System.Drawing.Point(0, 377)
        Me.stsBar.Name = "stsBar"
        Me.stsBar.Panels.AddRange(New System.Windows.Forms.StatusBarPanel() {Me.StatusBarPanel1})
        Me.stsBar.ShowPanels = True
        Me.stsBar.Size = New System.Drawing.Size(616, 24)
        Me.stsBar.TabIndex = 8
        '
        'StatusBarPanel1
        '
        Me.StatusBarPanel1.Name = "StatusBarPanel1"
        Me.StatusBarPanel1.Width = 608
        '
        'btnClear
        '
        Me.btnClear.Location = New System.Drawing.Point(496, 304)
        Me.btnClear.Name = "btnClear"
        Me.btnClear.Size = New System.Drawing.Size(88, 24)
        Me.btnClear.TabIndex = 9
        Me.btnClear.Text = "ログのクリア"
        '
        'menuMain
        '
        Me.menuMain.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.MenuItem1, Me.MenuItem2, Me.MenuItem3})
        '
        'MenuItem1
        '
        Me.MenuItem1.Index = 0
        Me.MenuItem1.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.menuPictureSave, Me.menuLogSave, Me.MenuItem6, Me.menuExit})
        Me.MenuItem1.Text = "ファイル"
        '
        'menuPictureSave
        '
        Me.menuPictureSave.Index = 0
        Me.menuPictureSave.Text = "画像の保存"
        '
        'menuLogSave
        '
        Me.menuLogSave.Index = 1
        Me.menuLogSave.Text = "ログの保存"
        '
        'MenuItem6
        '
        Me.MenuItem6.Index = 2
        Me.MenuItem6.Text = "-"
        '
        'menuExit
        '
        Me.menuExit.Index = 3
        Me.menuExit.Text = "終了"
        '
        'MenuItem2
        '
        Me.MenuItem2.Index = 1
        Me.MenuItem2.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.menuProviderSetting, Me.menuMailSetting})
        Me.MenuItem2.Text = "設定"
        '
        'menuProviderSetting
        '
        Me.menuProviderSetting.Index = 0
        Me.menuProviderSetting.Text = "プロバイダ"
        '
        'menuMailSetting
        '
        Me.menuMailSetting.Index = 1
        Me.menuMailSetting.Text = "メール"
        '
        'MenuItem3
        '
        Me.MenuItem3.Index = 2
        Me.MenuItem3.MenuItems.AddRange(New System.Windows.Forms.MenuItem() {Me.menuVersion})
        Me.MenuItem3.Text = "ヘルプ"
        '
        'menuVersion
        '
        Me.menuVersion.Index = 0
        Me.menuVersion.Text = "バージョン情報"
        '
        'GroupBox1
        '
        Me.GroupBox1.Controls.Add(Me.pctBox)
        Me.GroupBox1.Location = New System.Drawing.Point(8, 8)
        Me.GroupBox1.Name = "GroupBox1"
        Me.GroupBox1.Size = New System.Drawing.Size(352, 280)
        Me.GroupBox1.TabIndex = 10
        Me.GroupBox1.TabStop = False
        Me.GroupBox1.Text = "カメラ画像"
        '
        'GroupBox2
        '
        Me.GroupBox2.Controls.Add(Me.txtLog)
        Me.GroupBox2.Location = New System.Drawing.Point(368, 8)
        Me.GroupBox2.Name = "GroupBox2"
        Me.GroupBox2.Size = New System.Drawing.Size(240, 280)
        Me.GroupBox2.TabIndex = 11
        Me.GroupBox2.TabStop = False
        Me.GroupBox2.Text = "ログ"
        '
        'GroupBox3
        '
        Me.GroupBox3.Controls.Add(Me.barThreshold)
        Me.GroupBox3.Location = New System.Drawing.Point(8, 296)
        Me.GroupBox3.Name = "GroupBox3"
        Me.GroupBox3.Size = New System.Drawing.Size(352, 72)
        Me.GroupBox3.TabIndex = 12
        Me.GroupBox3.TabStop = False
        Me.GroupBox3.Text = "感度設定"
        '
        'frmMain
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 12)
        Me.ClientSize = New System.Drawing.Size(616, 401)
        Me.Controls.Add(Me.GroupBox3)
        Me.Controls.Add(Me.GroupBox2)
        Me.Controls.Add(Me.GroupBox1)
        Me.Controls.Add(Me.btnClear)
        Me.Controls.Add(Me.stsBar)
        Me.Controls.Add(Me.btnStop)
        Me.Controls.Add(Me.btnStart)
        Me.MaximizeBox = False
        Me.Menu = Me.menuMain
        Me.MinimizeBox = False
        Me.Name = "frmMain"
        Me.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Text = "遠隔監視システム"
        CType(Me.pctBox, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.barThreshold, System.ComponentModel.ISupportInitialize).EndInit()
        CType(Me.StatusBarPanel1, System.ComponentModel.ISupportInitialize).EndInit()
        Me.GroupBox1.ResumeLayout(False)
        Me.GroupBox2.ResumeLayout(False)
        Me.GroupBox2.PerformLayout()
        Me.GroupBox3.ResumeLayout(False)
        Me.GroupBox3.PerformLayout()
        Me.ResumeLayout(False)

    End Sub

#End Region

    ' CAOエンジン
    Private m_caoEng As CaoEngine
    ' CAOワークスペース
    Private m_caoWS As CaoWorkspace
    ' USBカメラのCAOコントローラ
    Private WithEvents m_ctrlCamera As CaoController
    ' カメラ画像のCAOファイル
    Private m_filePicture As CaoFile
    ' カメラの感度設定CAO変数
    Private m_varThreshold As CaoVariable
    ' 画像のバイナリデータ
    Private m_bArray() As Byte
    ' ログバッファ
    Private m_strLog As StringBuilder

    '*********************************************************************
    '関数名称  ：初期化処理
    '機能      ：アプリケーションの初期化をおこなう
    '引数      ：sender
    '            e
    '戻り値    ：なし
    '備考      ：フォームが生成されたときに呼び出される
    '*********************************************************************
    Private Sub frmMain_Load(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            'CAOエンジンとCAOワークスペースの作成
            m_caoEng = New CaoEngine
            m_caoWS = m_caoEng.Workspaces.Item(0)
            m_strLog = New StringBuilder
            setButton(False)
            logWrite("CAOエンジンを生成しました")
        Catch ex As Exception
            MessageBox.Show( _
                        "初期化処理に失敗しました" & vbCrLf & ex.Message, _
                        "CAOエラー", _
                        MessageBoxButtons.OK, _
                        MessageBoxIcon.Error)
            Me.Close()
        End Try
    End Sub

    '*********************************************************************
    '関数名称  ：計測開始処理
    '機能      ：カメラプロバイダに接続をおこない画像計測を開始する
    '引数      ：sender
    '            e
    '戻り値    ：なし
    '備考      ：開始ボタンが押されたときに呼び出される
    '*********************************************************************
    Private Sub btnStart_Click(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles btnStart.Click
        'コントロール作成
        Try
            Dim provInfo As ProviderInfo
            provInfo = ProviderInfo.GetInstance
            ' USBカメラプロバイダへの接続
            m_ctrlCamera = m_caoWS.AddController(provInfo.provName, _
                    provInfo.provID, provInfo.provMachine, provInfo.provParam)
            ' イベントハンドラの設定
            AddHandler m_ctrlCamera.OnMessage, _
                        AddressOf m_ctrlCamera_OnMessage
            ' CAOファイルの取得
            m_filePicture = m_ctrlCamera.AddFile("Picture")
            ' CAO変数の取得
            m_varThreshold = m_ctrlCamera.AddVariable("Threshold")
            setPicture()
            setButton(True)
            logWrite("プロバイダに接続しました")
            m_varThreshold.Value = barThreshold.Value
            stsBar.Panels(0).Text = "感度を" & barThreshold.Value & "に設定しました"
        Catch ex As Exception
            MessageBox.Show( _
                    "プロバイダにアクセスできません" & vbCrLf & ex.Message, _
                    "警告", _
                    MessageBoxButtons.OK, _
                    MessageBoxIcon.Exclamation)
            logWrite("プロバイダにアクセスできません")
        End Try
    End Sub

    '*********************************************************************
    '関数名称  ：計測終了処理
    '機能      ：画像計測を終了しカメラプロバイダのリソースを開放する
    '引数      ：sender
    '            e
    '戻り値    ：なし
    '備考      ：終了ボタンが押されたときに呼び出される
    '*********************************************************************
    Private Sub btnStop_Click(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles btnStop.Click
        Try
            releaseCAO()
            setButton(False)
            logWrite("プロバイダを開放しました")
        Catch ex As Exception
            MessageBox.Show( _
                    "プロバイダを開放できません" & vbCrLf & ex.Message, _
                    "警告", _
                    MessageBoxButtons.OK, _
                    MessageBoxIcon.Exclamation)
            logWrite("プロバイダを開放できません")
        End Try
    End Sub

    '*********************************************************************
    '関数名称  ：ログクリア処理
    '機能      ：ログ用テキストボックスをクリアする
    '引数      ：sender
    '            e
    '戻り値    ：なし
    '備考      ：クリアボタンが押されたときに呼び出される
    '*********************************************************************
    Private Sub btnClear_Click(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles btnClear.Click
        m_strLog = New StringBuilder
        txtLog.Clear()
    End Sub

    '*********************************************************************
    '関数名称  ：感度変更処理
    '機能      ：カメラの検出感度を変更する
    '引数      ：sender
    '            e
    '戻り値    ：なし
    '備考      ：感度用スクロールバーをスクロールさせたときに呼び出される
    '*********************************************************************
    Private Sub barThreshold_Scroll(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles barThreshold.Scroll
        stsBar.Panels(0).Text = "感度を" & barThreshold.Value & "に変更しました"
        Try
            m_varThreshold.Value = barThreshold.Value
        Catch ex As Exception

        End Try
    End Sub

    '********************************************************************
    '関数名称  ：画像保存処理
    '機能      ：現在画面に表示中の画像を保存する
    '引数      ：sender
    '            e
    '戻り値    ：なし
    '備考      ：メニューバーから「ファイル」→「画像の保存」
    '            を選択したときに呼び出される
    '*********************************************************************
    Private Sub menuPictureSave_Click(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles menuPictureSave.Click
        Try
            'ディレクトリの復元
            dlgSavePicture.RestoreDirectory = True
            '同名ファイルがあった場合メッセージ表示
            dlgSavePicture.OverwritePrompt = True
            dlgSavePicture.Filter = _
                "すべてのファイル(*.*)|*.*|ビットマップファイル(*.bmp)|*.bmp"
            'Filterプロパティの2つ目を表示
            dlgSavePicture.FilterIndex = 2
            'ダイアログボックスを表示し、［保存]をクリックした場合
            If dlgSavePicture.ShowDialog = Windows.Forms.DialogResult.OK Then

                'ビットマップファイルが選択されている場合
                If System.IO.Path.GetExtension(dlgSavePicture.FileName) = ".bmp" Then
                    Dim fs As FileStream = New FileStream( _
                           dlgSavePicture.FileName, FileMode.OpenOrCreate)
                    Dim w As BinaryWriter = New BinaryWriter(fs)
                    If Not m_bArray Is Nothing Then
                        w.Write(m_bArray)
                        stsBar.Panels(0).Text = "画像ファイルを保存しました"
                    Else
                        MessageBox.Show( _
                                "保存する画像が見つかりません", _
                                "警告", _
                                MessageBoxButtons.OK, _
                                MessageBoxIcon.Exclamation)
                        Exit Sub
                    End If
                    w.Close()
                Else
                    MessageBox.Show( _
                            "拡張子はbmpにしてください", _
                            "警告", _
                            MessageBoxButtons.OK, _
                            MessageBoxIcon.Exclamation)
                    Exit Sub
                End If
            End If
        Catch ex As Exception
            MessageBox.Show( _
                    "画像ファイルの保存に失敗しました" & vbCrLf & ex.Message, _
                    "警告", _
                    MessageBoxButtons.OK, _
                    MessageBoxIcon.Exclamation)
        End Try

    End Sub

    '*********************************************************************
    '関数名称  ：ログ保存処理
    '機能      ：現在画面に表示中のログを保存する
    '引数      ：sender
    '            e
    '戻り値    ：なし
    '備考      ：メニューバーから「ファイル」→「ログの保存」
    '            を選択したときに呼び出される
    '*********************************************************************
    Private Sub menuLogSave_Click(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles menuLogSave.Click
        Try
            'ディレクトリの復元
            dlgSaveLog.RestoreDirectory = True
            '同名ファイルがあった場合メッセージ表示
            dlgSaveLog.OverwritePrompt = True
            dlgSaveLog.Filter = _
                "すべてのファイル(*.*)|*.*|テキストファイル(*.txt)|*.txt"
            'Filterプロパティの2つ目を表示
            dlgSaveLog.FilterIndex = 2
            'ダイアログボックスを表示し、［保存]をクリックした場合
            If dlgSaveLog.ShowDialog = Windows.Forms.DialogResult.OK Then
                'テキストファイルが選択されている場合はファイルを保存する
                If System.IO.Path.GetExtension(dlgSaveLog.FileName) = ".txt" Then
                    Dim sw As New System.IO.StreamWriter(dlgSaveLog.FileName, False, _
                                                    System.Text.Encoding.Default)
                    If Not txtLog.Text = "" Then
                        sw.Write(txtLog.Text)
                        stsBar.Panels(0).Text = "ログファイルを保存しました"
                    Else
                        MessageBox.Show( _
                                "保存するログが見つかりません", _
                                "警告", _
                                MessageBoxButtons.OK, _
                                MessageBoxIcon.Exclamation)
                        Exit Sub
                    End If
                    sw.Close()
                Else
                    MessageBox.Show( _
                            "拡張子はtxtにしてください", _
                            "警告", _
                            MessageBoxButtons.OK, _
                            MessageBoxIcon.Exclamation)
                    Exit Sub
                End If
            End If
        Catch ex As Exception
            MessageBox.Show( _
                    "ログファイルの保存に失敗しました" & vbCrLf & ex.Message, _
                    "警告", _
                    MessageBoxButtons.OK, _
                    MessageBoxIcon.Exclamation)
        End Try

    End Sub

    '*********************************************************************
    '関数名称  ：アプリケーション終了処理
    '機能      ：アプリケーションを終了する
    '引数      ：sender
    '            e
    '戻り値    ：なし
    '備考      ：メニューバーから「ファイル」→「終了」
    '            を選択したときに呼び出される
    '*********************************************************************
    Private Sub menuExit_Click(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles menuExit.Click
        Try
            releaseCAO()
            'eng のWorkspaceコレクションからm_caoWSを削除
            If Not m_caoWS Is Nothing Then
                m_caoEng.Workspaces.Remove(m_caoWS.Index)
                m_caoWS = Nothing
            End If
            'eng を削除
            If Not m_caoEng Is Nothing Then
                m_caoEng = Nothing
            End If
        Catch ex As Exception
            MessageBox.Show( _
                    "終了処理に失敗しました" & vbCrLf & ex.Message, _
                    "警告", _
                    MessageBoxButtons.OK, _
                    MessageBoxIcon.Exclamation)
        End Try
        Me.Close()
    End Sub

    '*********************************************************************
    '関数名称  ：メール設定処理
    '機能      ：メールの設定用ダイアログを表示する
    '引数      ：sender
    '            e
    '戻り値    ：なし
    '備考      ：メニューバーから「設定」→「メール」
    '            を選択したときに呼び出される
    '*********************************************************************
    Private Sub menuMailSetting_Click(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles menuMailSetting.Click
        ' メール設定ダイアログを開く
        Dim frmMailSet As New frmMailSetting
        frmMailSet.ShowDialog()
    End Sub

    '*********************************************************************
    '関数名称  ：プロバイダ設定処理
    '機能      ：プロバイダの設定用ダイアログを表示する
    '引数      ：sender
    '            e
    '戻り値    ：なし
    '備考      ：メニューバーから「設定」→「プロバイダ」
    '            を選択したときに呼び出される
    '*********************************************************************
    Private Sub menuProviderSetting_Click(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles menuProviderSetting.Click
        ' プロバイダ設定ダイアログを開く
        Dim frmProvSet As New frmProviderSetting
        frmProvSet.ShowDialog()
    End Sub

    '*********************************************************************
    '関数名称  ：バージョン情報
    '機能      ：バージョン情報を表示する
    '引数      ：sender
    '            e
    '戻り値    ：なし
    '備考      ：メニューバーから「ヘルプ」→「バージョン」
    '            を選択したときに呼び出される
    '*********************************************************************
    Private Sub menuVersion_Click(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles menuVersion.Click
        MessageBox.Show("遠隔監視システム Version 1.0.0" & vbCrLf & vbCrLf & _
                        "copyright (c) 2005 System Engineering Consultants CO.,Ltd.", _
                        "遠隔監視システムのバージョン情報", _
                        MessageBoxButtons.OK, MessageBoxIcon.Information)
    End Sub

    '*********************************************************************
    '関数名称  ：イベント処理
    '機能      ：カメラプロバイダからのイベントを受付け画像を表示する
    '引数      ：sender
    '            e
    '戻り値    ：なし
    '備考      ：カメラプロバイダがイベントを発生させたときに呼び出される
    '*********************************************************************
    Private Sub m_ctrlCamera_OnMessage(ByVal pICaoMess As CaoMessage)
        logWrite("イベントが発生しました" & vbCrLf & "  " & pICaoMess.Value)
        Try
            ' 画像を取得してピクチャボックスに表示
            setPicture()
            ' メールを送信
            sendMail(pICaoMess.DateTime)
        Catch ex As Exception
            MessageBox.Show( _
                    "イベント受付に失敗しました" & vbCrLf & ex.Message, _
                    "警告", _
                    MessageBoxButtons.OK, _
                    MessageBoxIcon.Exclamation)
            logWrite("イベント受付に失敗しました")
            releaseCAO()
            setButton(False)
        End Try
    End Sub

    '*********************************************************************
    '関数名称  ：CAOの開放処理
    '機能      ：取得していたCAOのリソースを開放する
    '引数      ：なし
    '戻り値    ：なし
    '備考      ：なし
    '*********************************************************************
    Private Sub releaseCAO()
        Try
            ' CAO変数の開放
            If Not m_varThreshold Is Nothing Then
                m_ctrlCamera.Variables.Remove(m_varThreshold.Index)
                System.Runtime.InteropServices.Marshal. _
                            ReleaseComObject(m_varThreshold)
                m_varThreshold = Nothing
            End If
            ' CAOファイルの開放
            If Not m_filePicture Is Nothing Then
                m_ctrlCamera.Files.Remove(m_filePicture.Index)
                System.Runtime.InteropServices.Marshal. _
                            ReleaseComObject(m_filePicture)
                m_filePicture = Nothing
            End If
            ' CAOコントローラの開放
            If Not m_ctrlCamera Is Nothing Then
                ' イベントハンドラの開放
                RemoveHandler m_ctrlCamera.OnMessage, _
                            AddressOf m_ctrlCamera_OnMessage
                m_caoWS.Controllers.Remove(m_ctrlCamera.Index)
                System.Runtime.InteropServices.Marshal. _
                            ReleaseComObject(m_ctrlCamera)
                m_ctrlCamera = Nothing
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub


    '*********************************************************************
    '関数名称  ：ボタンの排他処理
    '機能      ：開始ボタンと終了ボタンの表示を制御する
    '引数      ：isStarted True  :開始ボタンを非表示，終了ボタンを表示
    '                      False :開始ボタンを表示，終了ボタンを非表示 
    '戻り値    ：なし
    '備考      ：なし
    '*********************************************************************
    Private Sub setButton(ByVal isStarted As Boolean)
        If isStarted = True Then
            ' 開始ボタンを非表示，終了ボタンを表示
            btnStart.Enabled = False
            btnStop.Enabled = True
        Else
            ' 開始ボタンを表示，終了ボタンを非表示 
            btnStart.Enabled = True
            btnStop.Enabled = False
        End If
    End Sub

    '*********************************************************************
    '関数名称  ：メールの送信処理
    '機能      ：メールの送信をおこなう
    '引数      ：message メールで送信するメッセージ
    '戻り値    ：なし
    '備考      ：なし
    '*********************************************************************
    Private Sub sendMail(ByVal message As String)
        Dim mailer As MailSender
        mailer = MailSender.GetInstance

        ' メール送信フラグが立っているときメール送信
        If (mailer.sendFlag = True) Then
            Try
                ' 添付ファイルフラグが立っていたら，添付ファイル付メール送信
                If (mailer.attachFlag = True) Then
                    Dim tempFileName As String
                    ' 一時ビットマップファイルを作成する
                    tempFileName = Application.StartupPath & "\Temp.bmp"
                    Dim fs As FileStream = New FileStream(tempFileName, FileMode.OpenOrCreate)
                    Dim w As BinaryWriter = New BinaryWriter(fs)
                    w.Write(m_bArray)
                    w.Close()

                    mailer.send("異常発生", message & "に異変が生じました", tempFileName)
                Else
                    mailer.send("異常発生", message & "に異変が生じました")
                End If
                MessageBox.Show("メールを送信しました", "実行結果")
                stsBar.Panels(0).Text = "メールを送信しました"
            Catch ex As Exception
                MessageBox.Show( _
                        "メール送信に失敗しました" & vbCrLf & ex.Message, _
                        "警告", _
                        MessageBoxButtons.OK, _
                        MessageBoxIcon.Exclamation)
                stsBar.Panels(0).Text = "メール送信に失敗しました"
            End Try

            'メールを送信したら処理を終了
            If Not m_ctrlCamera Is Nothing Then
                releaseCAO()
                setButton(False)
            End If
        End If

    End Sub

    '*********************************************************************
    '関数名称  ：ログ出力処理
    '機能      ：テキストボックスにログを出力する
    '引数      ：message 表示するログ
    '戻り値    ：なし
    '備考      ：なし
    '*********************************************************************
    Private Sub logWrite(ByVal message As String)
        ' 現在時刻を表示
        m_strLog.Append(Now.ToString & "." _
                & Now.Millisecond & vbCrLf & "  " & message & vbCrLf)
        txtLog.Text = m_strLog.ToString
        'カレット位置を末尾に移動
        txtLog.SelectionStart = txtLog.Text.Length
        'カレット位置までスクロール
        txtLog.ScrollToCaret()
    End Sub

    '*********************************************************************
    '関数名称  ：画像取得処理
    '機能      ：カメラプロバイダから画像を取得しピクチャボックスに表示
    '引数      ：なし
    '戻り値    ：なし
    '備考      ：なし
    '*********************************************************************
    Private Sub setPicture()
        Try
            ' 画像データの取得
            m_bArray = m_filePicture.Value
            ' バイナリデータからMemoryStreamオブジェクトを作成する
            Dim mstreamCur As New MemoryStream(m_bArray)
            ' ストリームからImageオブジェクトを作成し，ピクチャボックスに表示
            pctBox.Image = Image.FromStream(mstreamCur)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

End Class

