Public Class Frm_monitor

    Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Integer
    Declare Function PostMessage Lib "user32.dll" Alias "PostMessageA" (ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
    Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Integer)
    Private Const WM_QUIT = &H12
    Private Const WM_CLOSE = &H10

    Private ison As Boolean = False
    Private ismonitor As Boolean = False

    Dim totaltime As TimeSpan
    Dim ercnt As Integer = 0
    Dim starttime As Integer = 0

    Dim Xml As ArinXML

    Dim Createfile As String = ""
    Dim CreateStart As String = ""
    Dim killon As Boolean = False

    Dim fclose As Boolean = False
    Dim autoexit As Short = 0
    Dim runtime As String = Now.ToString
    Dim conffile As String = My.Application.Info.DirectoryPath & "\error.xml"
    Dim AutoClose As Boolean = False

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If Not AutoClose Then
            If MsgBox("정말로 종료하시겠습니까?", MsgBoxStyle.Information + MsgBoxStyle.OkCancel, "확인") = MsgBoxResult.Ok Then
            Else
                e.Cancel = True
            End If
        End If
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.ProgressBar1.Minimum = 0
        Me.ProgressBar1.Maximum = 6

        Dim a As New System.Text.StringBuilder
        a.AppendLine("이 프로그램은 VMS의 실행을 감지하는 프로그램입니다")
        a.AppendLine("VMS프로그램이 오류발생으로 작동을 멈출경우")
        a.AppendLine("초기화 및 재실행을 수행합니다.")
        a.AppendLine()
        Me.RichTextBox1.Text = a.ToString & vbCrLf
        totaltime = Nothing
        ercnt = 0
        Me.bt_monitor.PerformClick()
    End Sub

    Public Function RunProcess(ByVal 파일이름 As String, Optional ByVal 실행옵션 As String = vbNullString) As Boolean

        Try
            Dim RunP As Process
            Dim B As System.Diagnostics.ProcessStartInfo = New System.Diagnostics.ProcessStartInfo

            If FileIO.FileSystem.FileExists(파일이름) Then
                B.FileName = 파일이름
                B.WorkingDirectory = 파일이름.Substring(0, 파일이름.LastIndexOf("\"))
                B.Arguments = 실행옵션
                RunP = Process.Start(B)
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            Msg("ERROR_RUNPROCESS->" & ex.Message.ToString)
            Return False
        End Try

    
    End Function
    Public Function checkmyproc() As Process
        Try
            Dim Prc() As Process = Process.GetProcesses  '//현재프로세스배열을 가져온다.
            Dim MyPrc As Process
            For Each MyPrc In Prc
                If MyPrc.ProcessName.ToUpper.IndexOf("VMS.NET") <> -1 And MyPrc.ProcessName.ToUpper.IndexOf("VSHOST") = -1 Then
                    Return MyPrc
                End If
            Next
            Return Nothing
        Catch ex As Exception
            Msg("ERROR_CHECKMYPROC->" & ex.Message.ToString)
            Return Nothing
        End Try

    End Function
    Public Sub KillMyProc(ByVal 클래스명 As String)
        Try
            Dim Np As IntPtr
            Np = FindWindow(클래스명, vbNullString)
            'Me.lstOutput.Items.Add("WHND:" & Np.ToInt32.ToString)
            If Np = 0 Then
                'Form_Standard.MDIMessage.Text = "Cannot Find :" & 클래스명
                Exit Sub
            End If
            PostMessage(Np.ToInt32, WM_QUIT, 0&, 0&)
            Sleep(500)
        Catch ex As Exception
            Msg("ERROR_KIMMMYPROC->" & ex.Message.ToString)
        End Try

    End Sub
    Private Sub Msg(ByVal m As String)
        If Me.RichTextBox1.Text.Length > 10000 Then
            Try
                My.Computer.FileSystem.WriteAllText(My.Application.Info.DirectoryPath & "\" & Now.ToString("yyyyMMdd") & ".txt", Me.RichTextBox1.Text, True)
            Catch ex As Exception

            End Try
            Me.RichTextBox1.Text = ""
        End If

        Me.RichTextBox1.AppendText("[" & Now.ToString("yyyy-MM-dd HH:mm:ss") & "] " & m & vbCrLf)
        My.Application.DoEvents()
    End Sub
    Public Sub oKillMyProc(ByVal 프로세스명 As String)
        Try
            Dim Prc() As Process = Process.GetProcesses  '//현재프로세스배열을 가져온다.
            Dim MyPrc As Process
            Dim 파일명 As String = 프로세스명.Substring(프로세스명.LastIndexOf("\") + 1).ToUpper
            For Each MyPrc In Prc
                If (MyPrc.ProcessName & ".EXE").ToUpper = 파일명 Then

                    '    MsgBox(MyPrc.StartInfo.Fileame)
                    MyPrc.Kill()
                End If
            Next
            Sleep(500)
        Catch ex As Exception
            Msg("ERROR_OKILLMYPROC->" & ex.Message.ToString)
        End Try

    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Timer1.Enabled = False

       Dim Prc As Process = checkmyproc()
        If Prc Is Nothing Then

            '//프로세스가 없다.
            If Me.Timer2.Enabled = False Then
                autoexit += 1
                If autoexit > 3 Then
                    AutoClose = True
                    Me.Close()
                End If
            End If

            ison = False
            Me.bt_kill.Enabled = False
            Me.bt_run.Enabled = True
            'Me.Text = "noprocee"
            Me.status_run.ForeColor = Color.Gray
            If Me.starttime > 0 Then
                Me.status_run.ForeColor = Color.Orange
            End If


            If System.IO.File.Exists(conffile) Then ''//에러파일이 존재하는지 확인한다.
                Dim buffer = My.Computer.FileSystem.ReadAllText(conffile, System.Text.Encoding.Default).Trim
                If buffer <> "" Then
                    If buffer.Substring(0, 5) = "ERROR" Then
                        If Me.Timer2.Enabled = False Then   '//작동중이아니라면 실행한다.
                            Me.ProgressBar1.ForeColor = Color.Green
                            Me.Timer2.Enabled = True
                            Me.Timer2.Start()
                        End If
                    End If
                End If
            End If

        Else

            autoexit = 0
            Me.status_run.ForeColor = Color.Blue
            Me.bt_kill.Enabled = True
            Me.bt_run.Enabled = False

            ison = True
            Try
                dispalyinfo(Prc)
            Catch ex As Exception

            End Try
        End If

        Timer1.Enabled = True

    End Sub

    Private Sub dispalyinfo(ByVal prc As Process)
        Try

            Dim Eron As Boolean = False
            If System.IO.File.Exists(conffile) Then ''//에러파일이 존재하는지 확인한다.
                Dim buffer = My.Computer.FileSystem.ReadAllText(conffile, System.Text.Encoding.Default).Trim
                If buffer <> "" Then
                    If buffer.Substring(0, 5) = "ERROR" Then
                        If Me.Timer2.Enabled = False Then   '//작동중이아니라면 실행한다.
                            Eron = True
                        End If
                    End If
                End If
            End If

        

            If Eron Then
                Msg("VMS로부터 에러발생을 확인하였습니다")
                killon = True
            Else
                killon = False
            End If

            'Buf.AppendLine("PROCESS NAME:" & prc.ProcessName)
            'Buf.AppendLine("Start Time:" & prc.StartTime.ToString())
            'Buf.AppendLine("Total time:" & prc.TotalProcessorTime.ToString())
            'Buf.AppendLine("SessionID:" & prc.SessionId.ToString)
            'Buf.AppendLine("Response:" & prc.Responding)
            'Buf.AppendLine("Handle:" & prc.Handle.ToString)
            'Buf.AppendLine("Handle Count:" & prc.HandleCount)
            'Buf.AppendLine("prc.HasExited:" & prc.HasExited)
            'Buf.AppendLine("prc.Id:" & prc.Id)
            'Buf.AppendLine("prc.MainWindowTitle:" & prc.MainWindowTitle)
            'Buf.AppendLine("prc.PrivilegedProcessorTime.ToString:" & prc.PrivilegedProcessorTime.ToString)
            'Buf.AppendLine("prc.UserProcessorTime.ToString:" & prc.UserProcessorTime.ToString)
            'Buf.AppendLine("Error Count:" & Me.ercnt)


            If killon Then  '//10초를 넘도록


                Me.WindowState = FormWindowState.Normal

                Me.RichTextBox1.BackColor = Color.Orange
                Msg("VMS 재실쟁 대기중 : 잠시만 기다려주세요.")

                Me.Hide()
                Me.Show()
                My.Application.DoEvents()

                bt_kill.PerformClick()

                Sleep(2000)

                Try
                    System.IO.File.Delete(conffile)
                Catch ex As Exception

                End Try
                
            End If

            
        Catch ex As Exception
            Msg("ERROR_DISPLAYINFO_->" & ex.Message.ToString)
        End Try
    End Sub

    Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
        starttime += 1
        Me.ProgressBar1.Value = starttime
        If starttime > 5 Then
            Me.ProgressBar1.Value = 0
            Me.ProgressBar1.ForeColor = Color.Red
            Me.bt_run.PerformClick()
            starttime = 0
            Me.Timer2.Stop()
            Me.Timer2.Enabled = False
        End If
    End Sub


    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt_monitor.Click
        Me.ProgressBar1.Value = 0

        If Me.ismonitor Then
            Me.Timer1.Stop()
            Me.Timer1.Enabled = False
            Me.ismonitor = False
            Me.bt_monitor.Text = "모니터 시작"
            Msg("모니터링이 종료되었습니다.")
            Me.status_monitor.ForeColor = Color.Gray
        Else
            Me.Timer1.Enabled = True
            Me.Timer1.Start()
            Me.ismonitor = True
            Me.bt_monitor.Text = "모니터 종료"
            Msg("모니터링이 시작되었습니다.")
            Me.status_monitor.ForeColor = Color.Blue
        End If
    End Sub

    Private Sub ToolStripButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt_run.Click
        If Me.ison Then
            MsgBox("중복실행이므로 실행을 할 수 없습니다", MsgBoxStyle.Information, "확인")
        Else
            RunProcess(My.Application.Info.DirectoryPath & "\cVMS.NET.exe", "")
            Msg("VMS프로그램을 실행합니다")
            Me.WindowState = FormWindowState.Minimized
            Me.RichTextBox1.BackColor = Nothing
        End If
    End Sub

    Private Sub ToolStripButton3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bt_kill.Click
   
        Dim Prc As Process = checkmyproc()
        If Not Prc Is Nothing Then
            Try

                Try
                    System.IO.File.Delete(conffile)
                Catch ex As Exception

                End Try

                Prc.Kill()
                Me.ProgressBar1.ForeColor = Color.Green
                starttime = 0
                Me.Timer2.Enabled = True
                Me.Timer2.Start()
            Catch ex As Exception
                Msg("ERROR_BTKILL_->" & ex.Message.ToString)
            End Try
        End If
    End Sub

    Private Sub ToolStripButton1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
        Me.fclose = True
        End
    End Sub

End Class
