Public Class Form1

    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

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If fclose = False Then e.Cancel = True
        Me.WindowState = FormWindowState.Minimized

    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

        totaltime = Nothing
        ercnt = 0
        Me.bt_monitor.PerformClick()
    End Sub

    Public Function RunProcess(ByVal 파일이름 As String, Optional ByVal 실행옵션 As String = vbNullString) As Boolean
        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
    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("VPS.NET") <> -1 Then
                    Return MyPrc
                End If
            Next
            Return Nothing
        Catch ex As Exception
            Return Nothing
        End Try
     
    End Function

    Public Sub KillMyProc(ByVal 클래스명 As String)
        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)
    End Sub

    Private Sub Msg(ByVal m As String)
        Me.lb_msg.Text = m
        My.Application.DoEvents()
    End Sub
    Public Sub oKillMyProc(ByVal 프로세스명 As String)
        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)
    End Sub

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Dim Prc As Process = checkmyproc()
        If Prc Is Nothing Then

            '//프로세스가 없다.
            If Me.Timer2.Enabled = False Then
                autoexit += 1
                If autoexit > 3 Then
                    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

            Xml = New ArinXML(My.Application.Info.DirectoryPath & "\conf.xml")
            Dim File As String = Xml.Data("config", "autocreate")
            Dim Filename As String = Xml.Data("config", "createfile")
            Runtime = Xml.Data("config", "runtime")

            If File.Trim = "1" AndAlso Filename.Trim <> "" AndAlso Me.Timer2.Enabled = False Then
                Me.ProgressBar1.ForeColor = Color.Green
                Me.Timer2.Enabled = True
                Me.Timer2.Start()
            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
    End Sub

    Private Sub dispalyinfo(ByVal prc As Process)
        Xml = New ArinXML(My.Application.Info.DirectoryPath & "\conf.xml")
        Createfile = Xml.Data("config", "createfile")
        CreateStart = Xml.Data("config", "createstart")

     
        Dim Buf As New System.Text.StringBuilder
        Buf.AppendLine("NOW TIME:" & Now.ToString)

        If CreateStart.Trim <> "" AndAlso Createfile <> "" Then
            Buf.AppendLine(">> 생산중:" & Createfile)
            Buf.AppendLine(">> 판정시작:" & CreateStart)
            killon = True
            Me.status_create.ForeColor = Color.Blue
        Else
            Me.status_create.ForeColor = Color.Gray
            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 Me.totaltime = Nothing Then
            Me.totaltime = prc.TotalProcessorTime
        Else
            Dim ts As TimeSpan = prc.TotalProcessorTime - Me.totaltime

            Buf.AppendLine("Run Status:" & ts.ToString())


            If (Now - CDate(Me.runtime)).Seconds = 15 And killon Then
                Me.ProgressBar1.ForeColor = Color.Red
                ercnt += 1
                Me.ProgressBar1.Value = ercnt
            Else
                Me.ProgressBar1.Value = 0
                ercnt = 0
            End If

            Me.totaltime = prc.TotalProcessorTime

            If ercnt > 5 And killon Then  '//10초를 넘도록
                bt_kill.PerformClick()
            End If
        End If


        Buf.AppendLine(prc.ToString())

        Dim runtime As String = Xml.Data("config", "runtime")
        Msg("Running Time:" & runtime)

    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 bt_monitor_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    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("MONITOR OFF")
            Me.status_monitor.ForeColor = Color.Gray
        Else
            Me.Timer1.Enabled = True
            Me.Timer1.Start()
            Me.ismonitor = True
            Me.bt_monitor.Text = "모니터 종료"
            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 & "\vps.net.exe", "TINDEVIL")
        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

            Dim sta As Boolean = Prc.CloseMainWindow()
            If sta Then
                My.Application.DoEvents()

                While (1)
                    Dim P As Process = checkmyproc()
                    If P Is Nothing Then Exit While
                    My.Application.DoEvents()
                End While

                Xml = New ArinXML(My.Application.Info.DirectoryPath & "\conf.xml")
                Xml.Data("config", "autocreate") = "1"
                Xml.Data("config", "shutdown") = "0"

                Me.ProgressBar1.ForeColor = Color.Green
                starttime = 0
                Me.Timer2.Enabled = True
                Me.Timer2.Start()
            Else
                Xml = New ArinXML(My.Application.Info.DirectoryPath & "\conf.xml")
                Xml.Data("config", "autocreate") = "1"
                Xml.Data("config", "shutdown") = "0"

                Prc.Kill()
                Me.ProgressBar1.ForeColor = Color.Green
                starttime = 0
                Me.Timer2.Enabled = True
                Me.Timer2.Start()
            End If
        End If
    End Sub

    Private Sub ToolStrip1_ItemClicked(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles ToolStrip1.ItemClicked

    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
