Imports System
Imports System.IO
Imports System.IO.Ports
Imports System.Threading
Imports System.Net
Imports System.Net.Sockets
Imports System.Windows.Forms
Imports System.Management
Imports Microsoft.VisualBasic
Imports System.Drawing.Graphics
Imports Microsoft.Win32
Imports System.Speech
Imports System.Text
Imports ASCOM.Astrometry
Imports ASCOM.Utilities

Public Class Form1
    Public Version As String = "21.3"
    Public Version_Date As String = "23-Jun-2026"
    Dim Title As String = ""
    Public Cmd As String = ""
    Public Rsp As String = "(no reads have been issued)"

    Dim tcpClient As New System.Net.Sockets.TcpClient()
    Public networkStream As NetworkStream
    Dim IPaddr As IPAddress
    Dim SetIPaddr As IPAddress
    Dim TCPdataPort As Integer
    Dim TCPxPort As Integer = 7777
    Public SocketIsOpen As Boolean = False
    Public APnetwork As Boolean
    Public APipAddress As String
    Public APipPort As Integer
    Public APipPurgeTimeout As Integer
    Public MountRec(50) As Byte
    Public NumBytesRead As Integer = 0
    Public XPORTipAddress As String
    Public XPORTipPort As String


    Dim Slew_Cmd As String = ""
    Dim Slew_Rate As String = ""
    Dim SlewTime, FocusTime As Integer
    Dim Keyboard_Title As String = ""
    Public WithEvents KeyControl As New KeyButton()
    Dim KeyHeld As Boolean = False
    Dim IgnoreKey As Boolean = False
    Dim FocusCount, FocusRealCount As Integer
    Dim NorthSouthCount As Integer = 0
    Dim EastWestCount As Integer = 0
    Dim NSrealCount, EWrealCount As Integer
    Public WebH, WebW As Integer
    Public DomeLogH, DomeLogW As Integer
    Public DomeH, DomeW As Integer
    Public LogH, LogW As Integer
    Public MonitorH, MonitorW As Integer
    Public SaveRestoreH, SaveRestoreW As Integer
    Public FocusAgfH, FocusAgfW As Integer
    Public FocusMlH, FocusMlW As Integer
    Public Ding As Boolean = False
    Dim ts As TimeSpan
    Dim startDate As DateTime
    Dim endDate As DateTime
    Dim TimeStart, TimeEnd, TimeStartF, TimeEndF As Single
    Dim ProgN, ProgS, ProgE, ProgW, ProgI, ProgO As Single
    Dim M As String
    Public AP_DEC As String
    Public AP_RA As String
    Public AP_AZ As String
    Public AP_AL As String
    Public AP_AZ_Park4 As String
    Public AP_AL_Park4 As String
    Public RAtext, DECtext As String
    Public AP_MeridianDist As String
    Public AP_MeridianDeg As Double
    Public AP_MeridianTimeToStop As String
    Public MinsToMerStop As String
    Dim FormRestore(5) As Boolean
    Dim NeedToRestore As Boolean = False
    Public PosTopRD, PosLeftRD As Integer
    Public PosTopS, PosLeftS As Integer
    Public PosTopReCal, PosLeftReCal As Integer
    Dim SavedRA(4) As String
    Dim SavedDEC(5) As String
    Dim SavedRaFull As String = ""
    Dim SavedDecFull As String = ""
    Dim Ports As String()
    Dim Port As String
    Public NormColor, ActiveColor, RateInactiveColor, RateActiveColor As Color
    Public SaveHoverColor, SHC1, SHC2, SHC3, SHC4, SHC5, SHC6, SHC7 As Color
    Dim ExitButtonPressed As Boolean = False
    Dim SerialPortNameList As New List(Of String)()
    Dim Msg As String = ""
    Dim Resp As String = ""
    Dim Status As String = ""
    Public CurrentRate As String = ""
    Public MonitorCmd As Boolean = False
    Public TelescopeSide As String = ""
    Dim TelescopeLastRA, TelescopeCurRA As Single
    Dim TelescopeLastDEC, TelescopeCurDEC As Single
    Dim SlewRateIndex As Integer = 2
    Public TelescopeST As String = ""
    Public TelescopeLat As String = ""
    Dim TelescopeLon As String = ""
    Public MeridianOffset As String = ""
    Public Path As String
    Public DomeFilename As String
    Public DomesFileCustom As String
    Public DomeCurrent As Integer
    Dim DomeDefaultFilename As String = "\AP Mini Domes.txt"
    Dim InData As String
    Dim InData2 As String
    Public ErrorMsgBox As Boolean
    Public ReadTimeout As Integer
    Dim Lcolor As Color = Color.LightSkyBlue
    Dim Dcolor As Color = Color.LemonChiffon
    Dim Lcolor2 As Color = Color.LightSkyBlue
    Dim Dcolor2 As Color = Color.LightGreen
    Public Az_Value As String = "?"
    Dim T As String
    Public IgnoreButton As Boolean = False
    Public Talker As New Speech.Synthesis.SpeechSynthesizer
    Public FormLoading As Boolean = True
    Public SaveRestoreFilename As String
    Public ScreenWidth As Integer = 0
    Public ScreenHeight As Integer = 0
    Public RArate As String
    Public DECrate As String
    Public RArateInc As String
    Public DECrateInc As String
    Public TrackingRateFilename As String
    Public RAdrift As String
    Public DECdrift As String
    Public RAdriftHMS As String
    Public DECdriftHMS As String
    Public AdjustdRA As Boolean
    Public EWswitchCP3MeridianDelay As Boolean
    Dim CP3 As Boolean = False
    Dim CP3GOS As Boolean = False
    Public CP4 As Boolean = False
    Public CP4ip As Boolean = False
    Dim ServoVersion As String = ""
    Public GOSresp As String = ""
    Dim AP_CMD2 As String
    Dim AP_CMD2_RA As String
    Dim AP_CMD2_DEC As String
    Dim AP_RSP2_RA As String
    Dim AP_RSP2_DEC As String
    Dim InBuf2Len As Integer = 0
    Dim DelayWrite As Boolean = False
    Dim IgnoreResp As Boolean = False
    Dim J2000Resp As Boolean = False
    Dim J2000IgnoreDEC As Boolean = False
    Dim CheckBuffer2Running As Boolean = False
    Public StopOnConnect As Boolean
    Public StopOnPark As Boolean
    Public StopOnAltAzSlew As Boolean
    Public StartOnConnect As Boolean
    Const CtlNCO As Integer = 0
    Const CtlAGF As Integer = 1
    Dim GroupCenteringTop As Integer
    Dim GroupCenteringHeight As Integer
    Dim GroupTrackingTop As Integer
    Dim GroupTrackingHeight As Integer
    Public DurTimerPwrOff As Boolean
    Public DurTimerDisconnect As Boolean
    Public PwrRelay1 As Boolean
    Public PwrRelay2 As Boolean
    Public PwrRelay3 As Boolean
    Public PwrRelay1Name As String
    Public PwrRelay2Name As String
    Public PwrRelay3Name As String
    Public PwrBoxConnected As Boolean = False
    Public AbortStopWait As Boolean = False
    Public MerTimerPark As Boolean
    Public DurTimerPark As Boolean
    Public AltTimerPark As Boolean
    Public SetMeridianOffsetOnConnect As Boolean
    Public StopPHD As Boolean
    Dim MoveButtonRate As String = ""
    Public MsgDoNotShow As Boolean = False
    Public LogsFolder As String = ""
    Dim LogSaveError As Boolean = False
    Public DomeLastPos As Integer
    Public StopDurCnt As Integer = 0

    Public driver As ASCOM.DriverAccess.Telescope
    Dim DriverId As String = ""
    Public AscomConnect As Boolean = False
    Dim AscomRespSent As Boolean = False
    Dim p As Object

    Public MoveSize As Integer
    Public IncDecSize As Integer
    Public FocusASCOMid As String
    Public FocuserASCOMname As String

    Public MoveSize2 As Integer
    Public IncDecSize2 As Integer
    Public FocusASCOMid2 As String
    Public FocuserASCOMname2 As String

    Dim SaveRA1 As String = ""
    Dim SaveDEC1 As String = ""
    Dim SaveRA2 As String = ""
    Dim SaveDEC2 As String = ""

    Structure GOS
        Dim A As String
        Dim B As String
        Dim C As String
        Dim D As String
        Dim E As String
        Dim F As String
        Dim G As String
        Dim H As String
        Dim I As String
        Dim J As String
        Dim K As String
        Dim L As String
        Dim M As String
        Dim N As String
    End Structure

    Dim Resp_GOS As GOS

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim I, J As Integer
        Dim W As Integer = 0
        Dim H As Integer = 0
        Dim S As String
        Dim Kx, Ky, Kw, Kh As Integer
        Dim Kt As String

        Try
            TextBox1.Text = "v" & Version
            ToolTip1.SetToolTip(TextBox1, Version_Date)
            StatusLabel.Text = ""

            Me.Text = "AP Mini  v" & Version

            Dim HelpTT As String = "Click to access PDF document" & vbCrLf & "v" & Version & "  " & Version_Date
            Form_ControlP.ToolTip1.SetToolTip(Form_ControlP.ButtonShowPDF, HelpTT)

            If My.Settings.NeedUpgrade = True Then
                My.Settings.Upgrade()
            End If

            ' get screen size
            For Each Screen As Screen In System.Windows.Forms.Screen.AllScreens
                ScreenWidth = ScreenWidth + Screen.Bounds.Width
                ScreenHeight = ScreenHeight + Screen.Bounds.Height
            Next

            ' set speach rate
            Form_ControlP.ComboBoxSpeakRate.SelectedIndex = My.Settings.SpeakRate

            ' set NSEW button reverse check box
            CheckBoxFlipNS.Checked = My.Settings.NSbuttons
            CheckBoxFlipEW.Checked = My.Settings.EWbuttons

            ' Create button for keyboard control using arrows
            Kx = ButtonKeyboardDummy.Location.X
            Ky = ButtonKeyboardDummy.Location.Y
            Kw = ButtonKeyboardDummy.Size.Width
            Kh = ButtonKeyboardDummy.Size.Height
            Kt = ButtonKeyboardDummy.Text

            KeyControl.Size = New Size(Kw, Kh)
            KeyControl.Location = New Point(Kx, Ky)
            KeyControl.Text = New String(Kt)
            Me.Controls.Add(KeyControl)
            ToolTip1.SetToolTip(KeyControl, "Click to activate keyboard control")
            KeyControl.BringToFront()

            GroupBox1.Enabled = False
            TextBoxDome.Text = ""

            ContextMenuStrip1.Enabled = False

            ' get all com ports with OK status and put at top of com combo box
            BuildSerialPortComboBox()

            ' set saved com port
            S = My.Settings.ComPort
            J = -1
            For I = 0 To ToolStripComboBoxCom.Items.Count - 1
                If S = ToolStripComboBoxCom.Items(I) Then
                    J = I
                End If
            Next
            If J > -1 Then
                ToolStripComboBoxCom.SelectedIndex = J
            Else
                ToolStripComboBoxCom.SelectedIndex = 0
                TimerComNotFound.Enabled = True
            End If

            ' set saved com port2
            S = My.Settings.ComPort2
            J = -1
            For I = 0 To ComboBoxCom2.Items.Count - 1
                If S = ComboBoxCom2.Items(I) Then
                    J = I
                End If
            Next
            If J > -1 Then
                ComboBoxCom2.SelectedIndex = J
            Else
                ComboBoxCom2.SelectedIndex = 0
            End If
            ComboBoxCom2.Enabled = True

            ' set saved AGF Dome com port
            S = My.Settings.ComPortAGF
            J = -1
            For I = 0 To Form_Dome.ComboBoxAGF.Items.Count - 1
                If S = Form_Dome.ComboBoxAGF.Items(I) Then
                    J = I
                End If
            Next
            If J > -1 Then
                Form_Dome.ComboBoxAGF.SelectedIndex = J
            Else
                Form_Dome.ComboBoxAGF.SelectedIndex = 0
            End If

            ' set saved AGF dsr com port
            S = My.Settings.ComPortAGFdsr
            J = -1
            For I = 0 To Form_Dome.ComboboxAGFdsrCom.Items.Count - 1
                If S = Form_Dome.ComboboxAGFdsrCom.Items(I) Then
                    J = I
                End If
            Next
            If J > -1 Then
                Form_Dome.ComboboxAGFdsrCom.SelectedIndex = J
            Else
                Form_Dome.ComboboxAGFdsrCom.SelectedIndex = 0
            End If

            ' set saved AGF debug com port
            S = My.Settings.ComPortAGFdebug
            J = -1
            For I = 0 To Form_Dome.ComboBoxAGFdebugCom.Items.Count - 1
                If S = Form_Dome.ComboBoxAGFdebugCom.Items(I) Then
                    J = I
                End If
            Next
            If J > -1 Then
                Form_Dome.ComboBoxAGFdebugCom.SelectedIndex = J
            Else
                Form_Dome.ComboBoxAGFdebugCom.SelectedIndex = 0
            End If

            ' set saved AFG focuser box com port
            S = My.Settings.ComPortFocusAGF
            J = -1
            For I = 0 To Form_FocusAGF.ToolStripComboBoxCom.Items.Count - 1
                If S = Form_FocusAGF.ToolStripComboBoxCom.Items(I) Then
                    J = I
                End If
            Next
            If J > -1 Then
                Form_FocusAGF.ToolStripComboBoxCom.SelectedIndex = J
            Else
                Form_FocusAGF.ToolStripComboBoxCom.SelectedIndex = 0
            End If
            Form_FocusAGF.ToolStripComboBoxCom.Enabled = True

            ' set saved MoonLite stepper motor focuser
            S = My.Settings.ComPortFocusML
            J = -1
            For I = 0 To Form_FocusML.ToolStripComboBoxCom.Items.Count - 1
                If S = Form_FocusML.ToolStripComboBoxCom.Items(I) Then
                    J = I
                End If
            Next
            If J > -1 Then
                Form_FocusML.ToolStripComboBoxCom.SelectedIndex = J
            Else
                Form_FocusML.ToolStripComboBoxCom.SelectedIndex = 0
            End If
            If My.Settings.FocusMlSpeed1 < 0 Then My.Settings.FocusMlSpeed1 = 0
            If My.Settings.FocusMlSpeed2 < 0 Then My.Settings.FocusMlSpeed2 = 0
            If My.Settings.FocusMlInc1 < 0 Then My.Settings.FocusMlInc1 = 0
            If My.Settings.FocusMlInc2 < 0 Then My.Settings.FocusMlInc2 = 0
            Form_FocusML.ToolStripComboBoxCom.Enabled = True
            Form_FocusML.ShowCommandsSent.Checked = My.Settings.FocusMlShowCmds
            Form_FocusML.ComboBoxInc1.SelectedIndex = My.Settings.FocusMlInc1
            Form_FocusML.ComboBoxInc2.SelectedIndex = My.Settings.FocusMlInc2
            Form_FocusML.ComboBoxMotorSpeed1.SelectedIndex = My.Settings.FocusMlSpeed1
            Form_FocusML.ComboBoxMotorSpeed2.SelectedIndex = My.Settings.FocusMlSpeed2
            Form_FocusML.TabControl1.SelectedIndex = My.Settings.FocusMlMotor
            Form_FocusML.DualMotorController.Checked = My.Settings.MoonliteDualController

            Form_FocusML.ComboBoxRedBacklight.Items.Clear()
            For I = 0 To 255
                Form_FocusML.ComboBoxRedBacklight.Items.Add(I)
            Next
            Form_FocusML.ComboBoxRedBacklight.SelectedIndex = My.Settings.FocusMlLedBacklight

            ' Get main window position
            Me.Left = My.Settings.PosLeft
            Me.Top = My.Settings.PosTop

            ' Make sure form is on the screen
            If Me.Location.X < 0 Or Me.Location.Y < 0 Then
                Me.Location = New Point(0, 0)
            End If

            ' Get main window size
            H = My.Settings.SizeHeight
            W = My.Settings.SizeWidth
            If H > 0 Then Me.Height = H
            If W > 0 Then Me.Width = W

            ' Make sure main window is not off of screen
            If Me.Left + Me.Width > ScreenWidth Then
                Me.Left = ScreenWidth - Me.Width
            End If
            If Me.Top + Me.Height > ScreenHeight Then
                Me.Top = ScreenHeight - Me.Height
            End If

            WebH = My.Settings.WebHeight
            WebW = My.Settings.WebWidth
            If (WebH > 100) And (WebW > 100) Then
                Form_Web.Width = WebW
                Form_Web.Height = WebH
            End If

            DomeH = My.Settings.DomeHeight
            DomeW = My.Settings.DomeWidth
            If (DomeH > 200) And (DomeLogW > 200) Then
                Form_Dome.Width = DomeW
                Form_Dome.Height = DomeH
            End If

            DomeLogH = My.Settings.DomeLogHeight
            DomeLogW = My.Settings.DomeLogWidth
            If (DomeLogH > 100) And (DomeLogW > 100) Then
                Form_DOME_SENT_RESP_LOG.Width = DomeLogW
                Form_DOME_SENT_RESP_LOG.Height = DomeLogH
            End If

            LogH = My.Settings.LogHeight
            LogW = My.Settings.LogWidth
            If (LogH > 100) And (LogW > 100) Then
                Form_SENT_RESP_LOG.Width = LogW
                Form_SENT_RESP_LOG.Height = LogH
            End If

            MonitorH = My.Settings.MonitorHeight
            MonitorW = My.Settings.MonitorWidth
            If (MonitorH > 5) And (MonitorW > 10) Then
                Form_Monitor.Width = MonitorW
                Form_Monitor.Height = MonitorH
            End If

            SaveRestoreH = My.Settings.SaveRestoreHeight
            SaveRestoreW = My.Settings.SaveRestoreWidth
            If (SaveRestoreH > 100) And (SaveRestoreW > 100) Then
                Form_Save_Restore.Width = SaveRestoreW
                Form_Save_Restore.Height = SaveRestoreH
            End If

            FocusAgfH = My.Settings.FocusAgfHeight
            FocusAgfW = My.Settings.FocusAgfWidth
            If (FocusAgfH > 100) And (FocusAgfW > 100) Then
                Form_FocusAGF.Width = FocusAgfW
                Form_FocusAGF.Height = FocusAgfH
            End If

            FocusMlH = My.Settings.FocusMlHeight
            FocusMlW = My.Settings.FocusMlWidth
            If (FocusMlH > 100) And (FocusMlW > 100) Then
                Form_FocusML.Width = FocusMlW
                Form_FocusML.Height = FocusMlH
            End If

            ' Get Slew time ms
            NumericUpDownSlew.Value = My.Settings.SlewMs

            ' Get Focus time ms
            Form_FOCUS.NumericUpDownFocus.Value = My.Settings.FocusMs

            ' Get timed slew check
            CheckBoxSlewTime.Checked = My.Settings.TimedSlew

            ' Get timed focus check
            Form_FOCUS.CheckBoxFocusTime.Checked = My.Settings.TimedFocus

            ' Get search time and delay ms
            Form_SEARCH.SlewMs.Value = My.Settings.SearchMs
            Form_SEARCH.DelayMS.Value = My.Settings.SearchDelay

            ' Get variable slew and centering rates
            NumericUpDownRateC.Value = My.Settings.VarCenter
            NumericUpDownRate.Value = My.Settings.VarSlew

            ' Get positions of other forms
            PosTopS = My.Settings.PosTopS
            PosLeftS = My.Settings.PosLeftS
            PosTopReCal = My.Settings.PosTopReCal
            PosLeftReCal = My.Settings.PoslLeftReCal

            ' lock count text boxes
            TextBoxNScount.ReadOnly = True
            TextBoxEWcount.ReadOnly = True
            Form_FOCUS.TextBoxFocusCount.ReadOnly = True

            ' Always on top setting
            Form_ControlP.CheckBoxAlwaysOnTop.Checked = My.Settings.TopAlways
            If My.Settings.TopAlways = True Then
                AlwaysOnTop()
            End If

            ' Timed beep
            Form_ControlP.CheckBoxTimedBeep.Checked = My.Settings.TimedBeep
            'Ding = My.Settings.TimedBeep

            ' Initialize logs with time and program version
            Form_SENT_RESP_LOG.ResetLog()
            Form_DOME_SENT_RESP_LOG.ResetLog()

            ' Dome controller network settings
            Form_Dome.DomeTest = My.Settings.DomeNet
            S = My.Settings.DomeIP
            If S <> "" Then
                Form_Dome.RemoteIP = S
            End If
            Form_Dome.ToolStripTextBoxMask.Text = My.Settings.DomeLocateNet
            Form_Dome.ToolStripTextBoxIP.Text = My.Settings.DomeSetIP

            ' Diag values
            Form_DIAGS.NumericUpDownRun.Value = My.Settings.DiagRun
            Form_DIAGS.NumericUpDownDelay.Value = My.Settings.DiagDelay

            ' set dome track interval
            Form_Dome.NumericUpDownTrack.Value = My.Settings.TrackInterval

            ' set dome degrees sync
            Form_Dome.NumericUpDownSyncDeg.Value = My.Settings.DomeMoveDegAGF

            ' set domes file and entry(blank if using the default)
            DomesFileCustom = My.Settings.DomesFile
            DomeCurrent = My.Settings.DomeSettings

            ' set AGF absolute encoder
            Form_Dome.ButtonAGFencoder.Checked = My.Settings.AGFencoder

            ' set dome tab to show
            Form_Dome.TabControl1.SelectedIndex = My.Settings.DomeTab
            Form_Dome.SetMenuControl()

            ' set control tab to show
            Form_ControlP.TabControlP.SelectedIndex = My.Settings.ControlPtab

            ' load dome and scopes file
            Load_Domes()

            ' set dome AGF movement deg./sec.
            Form_Dome.MaskedTextBoxDegSec.Text = My.Settings.DomeDegSecAGF

            ' set dome tracking stop on timeout
            Form_Dome.StopTrackingOnTimeout.Checked = My.Settings.StopDomeTrackingOnTimeout

            ' set error message box setting
            Form_ControlP.CheckBoxErrorMsgBox.Checked = My.Settings.ErrorMsgBox
            If Form_ControlP.CheckBoxErrorMsgBox.Checked = True Then
                ErrorMsgBox = True
            Else
                ErrorMsgBox = False
            End If

            ' set 1st command delay setting
            Form_ControlP.CheckBoxDelay1stCommand.Checked = My.Settings.Delay1stCmd
            Form_ControlP.NumUpDownDelay1.Value = My.Settings.Delay1stCmdTime

            ' set dome track on startp setting
            AutoDomeTrackStartup.Checked = My.Settings.StartAutoDomeTrack

            ' set last command string
            Cmd = "No commands sent"

            ' set web browser type
            Form_Dome.InternalWebToolStripMenuItem.Checked = My.Settings.InternalWebBrowser

            ' save button background colors
            ActiveColor = My.Settings.MiniActivateColor
            NormColor = Color.Transparent

            RateActiveColor = My.Settings.RateColor
            RateInactiveColor = LabelSlewRate25.BackColor

            ' set read timeout
            ReadTimeout = My.Settings.ReadTimeout
            Form_ControlP.ReadTimeoutComboBox.SelectedIndex = ReadTimeout - 1
            StatusLabel.Text = ""

            ' set AGF read timeout
            Form_Dome.ComboBoxAGFtimeout.SelectedIndex = My.Settings.AGFReadTimeout

            ' set debug logging option for dome control
            Form_Dome.DebugLogging.Checked = My.Settings.DebugLogging
            Form_Dome.DebugLog = My.Settings.DebugLogging

            ' set part dome position
            Form_Dome.ComboBoxDomePark.SelectedIndex = My.Settings.Parkdome

            ' set duration timer will park dome option
            Form_Dome.DurTimerParksDome.Checked = My.Settings.DurTimerParkDome

            ' set duration timer saved park postition check box
            Select Case My.Settings.DurTimerParkPos
                Case 1
                    Form_ControlP.CheckBoxPark1.Checked = True
                Case 2
                    Form_ControlP.CheckBoxPark2.Checked = True
                Case 3
                    Form_ControlP.CheckBoxPark3.Checked = True
                Case 4
                    Form_ControlP.CheckBoxPark4.Checked = True
            End Select

            ' set dome log no duplicate entries setting
            Form_Dome.NoDupStatusEntries.Checked = My.Settings.DomeLogNoDups

            ' set stop tracking numbers
            Form_ControlP.TextBoxStopDur.Text = My.Settings.StopTrackingDur
            Form_ControlP.NumericUpDownStopDeg.Value = My.Settings.StopTrackingDeg

            ' set stop mount altitude limit
            Form_ControlP.NumericUpDownStopAlt.Value = My.Settings.StopTrackingAlt

            ' set stop tracking check boxes
            Form_ControlP.CheckBoxStopMeridian.Checked = My.Settings.StopTrackingCheckMer
            Form_ControlP.CheckBoxStopDur.Checked = My.Settings.StopTrackingCheckDur
            Form_ControlP.CheckBoxStopAlt.Checked = My.Settings.StopTrackingCheckAlt

            ' set save command log on exit option
            Form_SENT_RESP_LOG.CheckBoxSaveExit.Checked = My.Settings.SaveCommandLogExit

            ' set save dome command log on exit option
            Form_DOME_SENT_RESP_LOG.CheckBoxSaveExit.Checked = My.Settings.SaveDomeLogExit

            ' show status window if option set
            Form_ControlP.CheckBoxPosWinStartup.Checked = My.Settings.ShowStatusOnStartup
            If Form_ControlP.CheckBoxPosWinStartup.Checked = True Then
                ScopePositionToolStripMenuItem.PerformClick()
            End If

            ' set save restore filename
            SaveRestoreFilename = My.Settings.SaveRestoreFile
            If SaveRestoreFilename <> "" Then
                Form_Save_Restore.OpenFileDialog1.FileName = SaveRestoreFilename
                Form_Save_Restore.SaveFileDialog1.FileName = SaveRestoreFilename
                Form_Save_Restore.ReadSaveRestoreRADECfile(SaveRestoreFilename)
            End If

            ' set tracking rates
            RArate = My.Settings.RArate
            RArateInc = My.Settings.TrackingRAinc
            DECrate = My.Settings.DECrate
            DECrateInc = My.Settings.TrackingDECinc
            TrackingRateFilename = My.Settings.TrackingRateFile
            RAdrift = My.Settings.RAdrift
            DECdrift = My.Settings.DECdrift
            RAdriftHMS = My.Settings.RAdriftHMS
            DECdriftHMS = My.Settings.DECdriftHMS
            AdjustdRA = My.Settings.AdjustdRA

            ' set park 4 positions
            AP_AL_Park4 = My.Settings.Park4_AL
            AP_AZ_Park4 = My.Settings.Park4_AZ
            Dim P4tip As String = "Not set"
            If AP_AL_Park4 <> "" Then
                Dim AL As String = Mid(AP_AL_Park4, 5, 9)
                Dim AZ As String = Mid(AP_AZ_Park4, 5, 9)
                P4tip = "Altitude " & AL & vbCrLf & "Azimuth " & AZ
                Form_ControlP.CheckBoxPark4.Text = "Park4  (Alt:" & AL & "  Az:" & AZ & ")"
            End If
            Position4ToolStripMenuItem.Text = "Position 4" & vbCrLf & P4tip

            ' set EW switch function
            EWswitchCP3MeridianDelay = My.Settings.MeridianSwitchCP3
            Form_Dome.ButtonEWSwitchDoesCP3MeridianDelay.Checked = EWswitchCP3MeridianDelay

            ' com port2 adjust ra/dec from J2000 to current JD
            ToolStripMenuItemRDadjust.Checked = My.Settings.ComPort2AdjRaDecJD

            ' save last ra/dec if not null
            If AP_RA <> "" Then
                My.Settings.LastRaPos = AP_RA
            End If
            If AP_DEC <> "" Then
                My.Settings.LastDecPos = AP_DEC
            End If

            ' set saved ra/dec from last time program was used if valid
            Dim SavRa As String = My.Settings.LastRaPos
            Dim SavDec As String = My.Settings.LastDecPos
            If SavRa <> "" Then
                SavedRA(1) = Mid(SavRa, 1, 2)
                SavedRA(2) = Mid(SavRa, 4, 2)
                SavedRA(3) = Mid(SavRa, 7, 2)
                SavedRA(4) = Mid(SavRa, 10, 1)
                If Mid(SavDec, 1, 1) = "-" Then
                    SavedDEC(1) = 0
                    SavedDEC(2) = 1
                Else
                    SavedDEC(1) = 1
                    SavedDEC(2) = 0
                End If
                SavedDEC(3) = Mid(SavDec, 2, 2)
                SavedDEC(4) = Mid(SavDec, 5, 2)
                SavedDEC(5) = Mid(SavDec, 8, 2)
                SlewRestore.Enabled = True
                LabelShowRestore.Enabled = True
            Else
                SavedRA(1) = ""
                SavedRA(2) = ""
                SavedRA(3) = ""
                SavedRA(4) = ""
                SavedDEC(1) = ""
                SavedDEC(2) = ""
                SavedDEC(3) = ""
                SavedDEC(4) = ""
                SavedDEC(5) = ""
            End If

            ' set start tracking on connect option
            StartOnConnect = My.Settings.StartOnConnect
            Form_ControlP.CheckBoxStartTrackingOnConnect.Checked = StartOnConnect

            ' set stop tracking on Alt/Az slew option
            StopOnAltAzSlew = My.Settings.StopOnAltAzSlew
            Form_ControlP.CheckBoxStopOnAlAzSlew.Checked = StopOnAltAzSlew

            ' set stop tracking on park option
            StopOnPark = My.Settings.StopOnPark
            Form_ControlP.CheckBoxStopOnPark.Checked = StopOnPark

            ' set stop tracking on connect option
            StopOnConnect = My.Settings.StopOnConnect
            Form_ControlP.CheckBoxStopOnConnect.Checked = StopOnConnect

            ' set AGF Dome Controller ip address
            Form_Dome.AGFipAddress = My.Settings.AGFipAddress
            Form_Dome.AGFip.Text = Form_Dome.AGFipAddress

            ' set AP mount ip address
            APipAddress = My.Settings.APipAddress
            Form_ControlP.APip.Text = APipAddress

            ' set AP mount ip port
            APipPort = My.Settings.APipPort
            Form_ControlP.APport.Text = APipPort

            ' set AP mount ip purge timeout for connect
            APipPurgeTimeout = My.Settings.APipPurgeTimeout
            Form_ControlP.APpurge.Text = APipPurgeTimeout

            ' set XPort power box ip address
            XPORTipAddress = My.Settings.XportIP
            Form_ControlP.TextBoxXportIPaddress.Text = XPORTipAddress

            ' set XPort power box ip port
            XPORTipPort = My.Settings.XportPort
            Form_ControlP.TextBoxXportIPport.Text = XPORTipPort

            ' set focus windows buttons
            SetFocusButtons(False)

            ' try to conect and start dome tracking if option is set
            If AutoDomeTrackStartup.Checked = True Then
                TimerAutoDomeTrack.Enabled = True
            End If

            ' debug logging main window
            Form_ControlP.CheckBoxDebugLogging.Checked = My.Settings.DebugLoggingMain

            ' set agf dome last position
            If Form_Dome.CtlType = Form_Dome.CtlAGF Then
                Form_Dome.TrackBarDome.Value = My.Settings.DomeLastPos
                DomeLastPos = Form_Dome.TrackBarDome.Value
                Form_Dome.SetDomeAGFpos()
            End If

            ' set agf focus box timed options
            Form_FocusAGF.CheckBoxFocusTime.Checked = My.Settings.FocusAgfTimed
            Form_FocusAGF.NumericUpDownFocus.Value = My.Settings.FocusAgfTimems
            Form_FocusAGF.CheckBoxfocusTime2.Checked = My.Settings.FocusAgfTimed2
            Form_FocusAGF.NumericUpDownFocus2.Value = My.Settings.FocusAgfTimems2
            Form_FocusAGF.TabControl1.SelectedIndex = My.Settings.FocusAgfMotor
            Form_FocusAGF.CheckBoxRev1.Checked = My.Settings.FocusAgfRev1
            Form_FocusAGF.CheckBoxRev2.Checked = My.Settings.FocusAgfRev2
            Form_FocusAGF.ShowCommandsSentToolStripMenuItem.Checked = My.Settings.FocusAgfShowCmds

            ' set meridian offset
            MeridianOffset = My.Settings.MeridianOffset
            Form_Meridian.Mer = MeridianOffset
            Form_Meridian.FillMeridianOffset()

            ' set meridian offset on connect
            SetMeridianOffsetOnConnect = My.Settings.SetMeridianOffsetOnConnect
            Form_ControlP.CheckBoxSetMOonConnect.Checked = SetMeridianOffsetOnConnect

            ' set power relays and duration timer option
            PwrRelay1 = My.Settings.PwrRelay1
            PwrRelay2 = My.Settings.PwrRelay2
            PwrRelay3 = My.Settings.PwrRelay3
            PwrRelay1Name = My.Settings.PwrRelay1Name
            PwrRelay2Name = My.Settings.PwrRelay2Name
            PwrRelay3Name = My.Settings.PwrRelay3Name
            Form_ControlP.CheckBoxR1.Checked = PwrRelay1
            Form_ControlP.CheckBoxR2.Checked = PwrRelay2
            Form_ControlP.CheckBoxR3.Checked = PwrRelay3
            Form_ControlP.TextBoxR1Name.Text = PwrRelay1Name
            Form_ControlP.TextBoxR2Name.Text = PwrRelay2Name
            Form_ControlP.TextBoxR3Name.Text = PwrRelay3Name
            DurTimerPwrOff = My.Settings.DurTimerPwrOff
            Form_ControlP.CheckBoxDurPwrOff.Checked = DurTimerPwrOff

            ' set disconnect duration timer option
            DurTimerDisconnect = My.Settings.DurTimerDisconnect
            Form_ControlP.CheckBoxDisconnect.Checked = DurTimerDisconnect

            ' set park with meridian timer option
            MerTimerPark = My.Settings.MerTimerPark
            Form_ControlP.CheckBoxMerPark.Checked = MerTimerPark

            ' set park with duration timer option
            DurTimerPark = My.Settings.DurTimerPark
            Form_ControlP.CheckBoxDurPark.Checked = DurTimerPark

            ' set part with altitude timer option
            AltTimerPark = My.Settings.AltTimerPark
            Form_ControlP.CheckBoxAltPark.Checked = AltTimerPark

            ' set stop PHD 
            Form_ControlP.CheckBoxStopPHD.Checked = My.Settings.StopPHD
            Form_ControlP.TextBoxPHDname.Text = My.Settings.PHDname

            ' set control dome test values
            Form_ControlP.NumDegs.Value = My.Settings.DomeTestDeg
            Form_ControlP.NumWait.Value = My.Settings.DomeTestWait
            Form_ControlP.NumLoop.Value = My.Settings.DomeTestLoop
            If My.Settings.DomeTestDir = "CW" Then
                Form_ControlP.DirCW.Checked = True
            End If
            If My.Settings.DomeTestDir = "CCW" Then
                Form_ControlP.DirCCW.Checked = True
            End If
            Form_ControlP.CheckBoxToggle.Checked = My.Settings.DomeDiagToggle

            ' set focuser type
            ComboBoxFocuser.SelectedIndex = My.Settings.Focuser

            ' set ASCOM foucser #1 values
            MoveSize = My.Settings.MoveSize
            IncDecSize = My.Settings.IncDecSize
            FocusASCOMid = My.Settings.FocusASCOMid
            FocuserASCOMname = My.Settings.FocuserASCOMname

            ' set ASCOM foucser #2 values
            MoveSize2 = My.Settings.MoveSize2
            IncDecSize2 = My.Settings.IncDecSize2
            FocusASCOMid2 = My.Settings.FocusASCOMid2
            FocuserASCOMname2 = My.Settings.FocuserASCOMname2

            ' set ASCOM focus motor
            Form_FocusASCOM2.TabControl1.SelectedIndex = My.Settings.FocusASCOMmotor

            ' set AGF dome wheel bias 
            Form_Dome.TextBoxDomeWheelBias.Text = My.Settings.AGFbias

            ' set logs save folder
            LogsFolder = My.Settings.LogsFolder
            If LogsFolder = "" Then
                LogsFolder = My.Computer.FileSystem.SpecialDirectories.MyDocuments
            End If
            Form_ControlP.TextBoxLogsFolder.Text = LogsFolder

            ' Debug open AP command and dome command log windows
            If Form_ControlP.CheckBoxDebugLogging.Checked = True Then
                ToolStripMenuItem4.PerformClick()
                Form_Dome.CommandsSentResponseToolStripMenuItem1.PerformClick()
            End If

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly, "AP Mini Startup Error")

        End Try

        FormLoading = False

    End Sub

    Public Sub AutoDomeTrack()
        Dim Line As String = ""
        Dim LineTalk As String = ""
        Dim LC As Color = Color.Black

        If SerialPort1.IsOpen = False And SocketIsOpen = False And Form_Dome.SerialPort2.IsOpen = False And IsConnected = False Then
            Line = "Automatic dome tracking initializing"
            UpdateStatusLine(Line, LC)
            DomeToolStripMenuItem.PerformClick()
            'Application.DoEvents()
            Talker.SpeakAsync(Line)
            ButtonConnect.PerformClick()
            If SerialPort1.IsOpen = True Or SocketIsOpen = True Or IsConnected = True Then
                ButtonConnect2.PerformClick()
            End If
            GetScopeAzEl()
            If AP_AZ <> "" Then
                Select Case Form_Dome.TabControl1.SelectedIndex

                    Case CtlAGF
                        Form_Dome.ButtonAGFconnect.PerformClick()

                        If My.Settings.AGFemulator = True Then
                            Form_Dome.AGFdomeEmulatorMode.PerformClick()
                        End If

                        If Form_Dome.DomeResponse = "" Then
                            ButtonConnect.PerformClick()
                            If Form_Dome.SerialPort2.IsOpen Then
                                Form_Dome.ButtonAGFconnect.PerformClick()
                            End If
                            Dim DS As String = Form_Dome.StatusLabel.Text
                            Line = DS
                        Else
                            Form_Dome.ButtonDC.PerformClick()
                            'Form_Dome.ButtonSetCalcAGF.PerformClick()
                            Line = "Automatic dome tracking has started"
                            If Form_Dome.ConnectDSRport.Checked = False Then
                                Form_Dome.CheckBoxTrack.Checked = True
                            Else
                                Dim Ds As Integer = Form_Dome.SerialPort3.DsrHolding
                                If Ds = 0 Then
                                    LineTalk = "DSR switch has control, dome tracking disabled"
                                Else
                                    LineTalk = "DSR switch has control"
                                End If
                            End If
                        End If

                    Case CtlNCO
                        Form_Dome.ButtonDomeConnect.PerformClick()
                        If Form_Dome.DomeResponse = "" Then
                            ButtonConnect.PerformClick()
                            If Form_Dome.SerialPort2.IsOpen Then
                                Form_Dome.ButtonDomeConnect.PerformClick()
                            End If
                            LC = Color.DarkRed
                            Line = "Dome NCO controller no response"
                        Else
                            Form_Dome.ButtonDC.PerformClick()
                            Form_Dome.ButtonSetCalcAGF.PerformClick()
                            Form_Dome.CheckBoxTrack.Checked = True
                            Line = "Automatic dome tracking has started"
                        End If

                    Case Else
                        LC = Color.DarkRed
                        Line = "Dome controller type not set"
                End Select
            Else
                LC = Color.DarkRed
                Line = "Did not get azimuth from mount, aborted"
                If SerialPort1.IsOpen = True Or SocketIsOpen = True Or IsConnected = True Then
                    ButtonConnect.PerformClick()
                End If
            End If
        End If

        If Line <> "" Then
            UpdateStatusLine(Line, LC)
            Talker.Speak(Line)
        End If

        If LineTalk <> "" Then
            Talker.Speak(LineTalk)
        End If

        If Form_Dome.MaskedTextBoxDegSec.Text = 0 And Form_Dome.TabControl1.SelectedIndex = Form_Dome.CtlAGF Then
            Talker.Speak("Warning, dome rate is set to zero.")
        End If

        If CP3 = True And MeridianOffset <> "00:00:00.0#" And Form_ControlP.CheckBoxSetMOonConnect.Checked = True Then
            Talker.Speak("Meridian offset has been set.")
        End If

        KeyControl.Focus()

    End Sub

    Private Sub BuildSerialPortComboBox()
        Dim I As Integer

        ToolStripComboBoxCom.Items.Clear()
        ComboBoxCom2.Items.Clear()
        Form_Dome.ComboBoxAGF.Items.Clear()
        Form_Dome.ComboboxAGFdsrCom.Items.Clear()
        Form_Dome.ComboBoxAGFdebugCom.Items.Clear()
        Form_FocusAGF.ToolStripComboBoxCom.Items.Clear()
        Form_FocusML.ToolStripComboBoxCom.Items.Clear()

        ' get all com ports with OK status and put at top of com combo box
        GetComPorts()
        For I = 0 To SerialPortNameList.Count - 1
            ToolStripComboBoxCom.Items.Add(SerialPortNameList(I))
            ComboBoxCom2.Items.Add(SerialPortNameList(I))
            Form_Dome.ComboBoxAGF.Items.Add(SerialPortNameList(I))
            Form_Dome.ComboboxAGFdsrCom.Items.Add(SerialPortNameList(I))
            Form_Dome.ComboBoxAGFdebugCom.Items.Add(SerialPortNameList(I))
            Form_FocusAGF.ToolStripComboBoxCom.Items.Add(SerialPortNameList(I))
            Form_FocusML.ToolStripComboBoxCom.Items.Add(SerialPortNameList(I))
        Next

        ToolStripComboBoxCom.Items.Add("Network")
        ToolStripComboBoxCom.Items.Add("ASCOM")
        ComboBoxCom2.Items.Add("None")
        Form_Dome.ComboBoxAGF.Items.Add("Network")
        Form_Dome.ComboboxAGFdsrCom.Items.Add("None")
        Form_Dome.ComboBoxAGFdebugCom.Items.Add("None")
        Form_FocusAGF.ToolStripComboBoxCom.Items.Add("None")
        Form_FocusML.ToolStripComboBoxCom.Items.Add("None")
        ' put all possible com ports below found com ports
        For I = 1 To 255
            ToolStripComboBoxCom.Items.Add("COM" & I)
            ComboBoxCom2.Items.Add("COM" & I)
            Form_Dome.ComboBoxAGF.Items.Add("COM" & I)
            Form_Dome.ComboboxAGFdsrCom.Items.Add("COM" & I)
            Form_Dome.ComboBoxAGFdebugCom.Items.Add("COM" & I)
            Form_FocusAGF.ToolStripComboBoxCom.Items.Add("COM" & I)
            Form_FocusML.ToolStripComboBoxCom.Items.Add("COM" & I)
        Next
        ToolStripComboBoxCom.DropDownWidth = GetLongestItemWidth(ToolStripComboBoxCom)
        ComboBoxCom2.DropDownWidth = GetLongestItemWidth(ToolStripComboBoxCom)
        Form_Dome.ComboBoxAGF.DropDownWidth = GetLongestItemWidth(ToolStripComboBoxCom)
        Form_Dome.ComboboxAGFdsrCom.DropDownWidth = GetLongestItemWidth(ToolStripComboBoxCom)
        Form_Dome.ComboBoxAGFdebugCom.DropDownWidth = GetLongestItemWidth(ToolStripComboBoxCom)
        Form_FocusAGF.ToolStripComboBoxCom.DropDownWidth = GetLongestItemWidth(ToolStripComboBoxCom)
        Form_FocusML.ToolStripComboBoxCom.DropDownWidth = GetLongestItemWidth(ToolStripComboBoxCom)

    End Sub


    Private Sub GetComPorts()
        Dim I, J As Integer

        ' get all com ports with OK status
        Try
            Dim moSearch As New Management.ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_PnPEntity")
            Dim moCollect As Management.ManagementObjectCollection = moSearch.Get()
            Dim SerialPortName As String
            For Each moObject As Management.ManagementObject In moCollect
                SerialPortName = moObject.GetPropertyValue("Name")
                I = InStr(SerialPortName, "(COM")
                If moObject.GetPropertyValue("Status") <> "OK" Then
                    I = 0
                End If
                If I > 0 Then
                    J = InStr(SerialPortName, ")")
                    SerialPortNameList.Add(Mid(SerialPortName, I + 1, J - I - 1) & "     " & Mid(SerialPortName, 1, I - 2))
                End If
            Next
            SerialPortNameList.Sort()
        Catch ex As Exception
            StatusLabel.Text = ex.Message
        End Try

    End Sub

    Private Function GetLongestItemWidth(ByVal combo As ToolStripComboBox) As Integer
        Dim longest As Integer
        Dim str As String
        Dim g As Graphics = Graphics.FromImage(New Bitmap(1, 1))

        'Enumerate the items in the combo
        For Each str In combo.Items
            Dim wid As Integer

            'Get the width of the item; if it's longer than the
            'longest one so far, store it.
            wid = g.MeasureString(str, combo.Font).Width
            If wid > longest Then longest = wid
        Next
        If combo.Items.Count > combo.MaxDropDownItems Then
            longest = longest + SystemInformation.VerticalScrollBarWidth
        End If

        Return longest
    End Function

    ''' <summary>
    ''' Gets a value indicating whether this instance is connected.
    ''' </summary>
    ''' <value>
    ''' 
    ''' <c>true</c> if this instance is connected; otherwise, <c>false</c>.
    ''' 
    ''' </value>
    Public ReadOnly Property IsConnected() As Boolean
        Get
            If Me.driver Is Nothing Then Return False
            Return driver.Connected
        End Get
    End Property


    Private Sub ASCOM_Choose()
        DriverId = ASCOM.DriverAccess.Telescope.Choose(My.Settings.DriverId)

        If DriverId <> "" Then
            My.Settings.DriverId = DriverId
            StatusLabel.Text = DriverId
        End If

    End Sub

    Private Sub ButtonChoose_Click(sender As System.Object, e As System.EventArgs) Handles ButtonChoose.Click
        If IsConnected = False Then
            ASCOM_Choose()
        Else
            StatusLabel.Text = My.Settings.DriverId
        End If

    End Sub

    Private Sub ButtonConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonConnect.Click
        Dim ComPort As String

        ComPort = Trim(Microsoft.VisualBasic.Left(ToolStripComboBoxCom.Items(ToolStripComboBoxCom.SelectedIndex), 6))

        If ComPort = "ASCOM" Then
            'ASCOM connection to AP mount
            If (IsConnected) = False Then
                Try
                    StatusLabel.Text = "Opening " & My.Settings.DriverId
                    Application.DoEvents()
                    InData = ""
                    APnetwork = False
                    driver = New ASCOM.DriverAccess.Telescope(My.Settings.DriverId)
                    driver.Connected = True
                    AscomConnect = True
                    SetConnect()
                    Form_ControlP.ButtonDateTime.Enabled = False
                    'SyncToolStripMenuItem.Enabled = False
                    MeridianOffsetButton.Enabled = False
                    GTOCP3TrackingRateButton.Enabled = False
                Catch ex As Exception
                    UpdateStatusLine("Connect error: '" & ex.Message & "'", Color.DarkRed)
                End Try
            Else
                driver.Connected = False
                driver.Dispose()
                driver = Nothing
                AscomConnect = False
                StatusLabel.Text = "Disconnected " & My.Settings.DriverId
                SetDisconnect()
                Form_ControlP.ButtonDateTime.Enabled = True
                MeridianOffsetButton.Enabled = True
                GTOCP3TrackingRateButton.Enabled = True
            End If
        End If

        If ComPort = "Networ" Then
            ' Network connection to AP mount
            If SocketIsOpen = False Then
                Me.Cursor = Cursors.WaitCursor
                Try
                    TCPdataPort = APipPort
                    If APipPort = 23 Then       ' ethernet connection port 23 is a CP4
                        CP4ip = True
                    Else
                        CP4ip = False
                    End If
                    UpdateStatusLine("Connecting to mount via network, 30 second timeout", Color.Black)
                    UpdateStatusLine("IP=" & APipAddress & ", Port=" & TCPdataPort, Color.Black)
                    Application.DoEvents()
                    tcpClient = New System.Net.Sockets.TcpClient()
                    IPaddr = IPAddress.Parse(APipAddress)
                    tcpClient.Connect(IPaddr, TCPdataPort)
                    networkStream = tcpClient.GetStream
                    ' purge the receive buffer from the AP mount to remove power up/down data
                    tcpClient.ReceiveTimeout = APipPurgeTimeout
                    Try
                        UpdateStatusLine("Purge AP mount read buffer " & APipPurgeTimeout & "ms", Color.Black)
                        NumBytesRead = networkStream.Read(MountRec, 0, MountRec.Length)
                        Resp = Encoding.ASCII.GetString(MountRec, 0, NumBytesRead)
                        UpdateStatusLine("Read buffer data = " & Resp, Color.Black)
                    Catch
                    End Try
                    ' set normal read timeout and continue
                    tcpClient.ReceiveTimeout = ReadTimeout * 1000
                    SocketIsOpen = True
                    APnetwork = True
                    StatusLabel.Text = "Connected network"
                    SetConnect()
                Catch ex As Exception
                    UpdateStatusLine("Connect network error: '" & ex.Message & "'", Color.DarkRed)
                End Try
            Else
                tcpClient.Close()
                SocketIsOpen = False
                StatusLabel.Text = "Disconnected network"
                SetDisconnect()
            End If
        End If

        If Mid(ComPort, 1, 3) = "COM" Then
            ' Serial connection to AP mount
            If SerialPort1.IsOpen = False Then
                Try
                    SerialPort1.PortName = ComPort
                    StatusLabel.Text = "Opening " & SerialPort1.PortName
                    Application.DoEvents()
                    InData = ""
                    SerialPort1.Open()
                    SerialPort1.DiscardInBuffer()
                    APnetwork = False
                    SetConnect()
                Catch ex As Exception
                    UpdateStatusLine("Connect error: '" & ex.Message & "'", Color.DarkRed)
                End Try
            Else
                SerialPort1.Close()
                StatusLabel.Text = "Disconnected " & SerialPort1.PortName
                SetDisconnect()
            End If

        End If


        If SerialPort2.IsOpen = True Then
            COMport2Connect()
        End If

        Form_Dome.CheckBoxTrack.Checked = False
        Me.Cursor = Cursors.Default

    End Sub

    Private Sub SetConnect()
        ButtonConnect.Text = "Disconnect"
        ToolStripComboBoxCom.Enabled = False
        LogScope("Status = ", Color.Black, StatusLabel.Text)
        If Form_ControlP.CheckBoxDelay1stCommand.Checked = True Then
            Thread.Sleep(Form_ControlP.NumUpDownDelay1.Value)
        End If
        AP_Command("Init")
        AP_Command("SetFormat")
        Thread.Sleep(200)
        GroupBox1.Enabled = True
        ContextMenuStrip1.Enabled = True
        Form_DIAGS.ButtonRA.Enabled = True
        Form_DIAGS.ButtonDEC.Enabled = True
        Form_ControlP.ButtonMountDiag.Enabled = True
        Form_ControlP.ButtonDateTime.Enabled = True
        Form_ControlP.ButtonQuery.Enabled = True
        SyncToolStripMenuItem.Enabled = True
        SetFocusButtons(True)
        Form_FOCUS.ZeroCounterFocus()
        ZeroCounterNS()
        ZeroCounterEW()
        If StopOnConnect = True Then
            RadioButtonStop.PerformClick()
        End If
        If StartOnConnect = True Then
            RadioButtonSideral.PerformClick()
        End If
        AP_Command("GetVersion")
        Dim SavVer As String = StatusLabel.Text
        If CP3 = True Then
            If SetMeridianOffsetOnConnect = True Then
                Form_Meridian.SetMeridianOffset(False)
            End If
        End If
        StatusLabel.Text = SavVer
        Form_Dome.ButtonGetAz.Enabled = True
        Form_Dome.ButtonDC.Enabled = True
        If Form_Dome.SocketIsOpen = True Or Form_Dome.SerialPort2.IsOpen = True Then
            Form_Dome.ButtonDomeSync.Enabled = True
            Form_Dome.CheckBoxTrack.Enabled = True
            Form_Dome.ButtonMoveDomeToCalc.Enabled = True
        End If
        TelescopeLastRA = 0
        TelescopeCurRA = 0
        TelescopeLastDEC = 0
        TelescopeCurDEC = 0
        If Form_Monitor.Visible = True Then
            Form_Monitor.ButtonUpdate.PerformClick()
        End If
        If CP3GOS = True Then
            AP_Command("MountOperatingStatus")
        End If

        MsgDoNotShow = False

    End Sub

    Private Sub SetDisconnect()
        If Form_DIAGS.RArun = True Then
            Form_DIAGS.ButtonRA.PerformClick()
        End If
        If Form_DIAGS.DECrun = True Then
            Form_DIAGS.ButtonDEC.PerformClick()
        End If
        StopAny()
        ButtonConnect.Text = "Connect"
        ToolStripComboBoxCom.Enabled = True
        LogScope("Status = ", Color.Black, StatusLabel.Text)
        GroupBox1.Enabled = False
        ContextMenuStrip1.Enabled = False
        Form_DIAGS.ButtonRA.Enabled = False
        Form_DIAGS.ButtonDEC.Enabled = False
        Form_ControlP.ButtonDateTime.Enabled = False
        Form_ControlP.ButtonMountDiag.Enabled = False
        Form_ControlP.ButtonQuery.Enabled = False
        SyncToolStripMenuItem.Enabled = False
        Form_FOCUS.RadioButtonUnk.Checked = True
        SetFocusButtons(False)
        Form_SEARCH.Visible = False
        Form_Dome.ButtonGetAz.Enabled = False
        Form_Dome.ButtonDomeSync.Enabled = False
        Form_Dome.CheckBoxTrack.Enabled = False
        Form_Dome.ButtonDC.Enabled = False
        Form_Dome.ButtonMoveDomeToCalc.Enabled = False

    End Sub



    Private Sub SetFocusButtons(ByVal State As Boolean)
        Form_FOCUS.ButtonFocusIn.Enabled = State
        Form_FOCUS.ButtonFocusOut.Enabled = State
        Form_FOCUS.ButtonFocusStop.Enabled = State
        Form_FOCUS.RadioButtonFocusFast.Enabled = State
        Form_FOCUS.RadioButtonFocusSlow.Enabled = State
        Form_FOCUS.ButtonFocusRestore.Enabled = State

    End Sub

    Private Sub ButtonConnect2_Click(sender As System.Object, e As System.EventArgs) Handles ButtonConnect2.Click
        If SerialPort1.IsOpen = True Or SocketIsOpen = True Or IsConnected = True Then
            COMport2Connect()
        Else
            StatusLabel.Text = "Main COM port not connected"
        End If

    End Sub

    Private Sub COMport2Connect()
        Dim ComPort2 As String

        ComPort2 = Trim(Microsoft.VisualBasic.Left(ComboBoxCom2.Items(ComboBoxCom2.SelectedIndex), 6))
        If Microsoft.VisualBasic.Left(ComPort2, 1) = "C" Then
            If SerialPort2.IsOpen = False Then
                SerialPort2.PortName = ComPort2
                StatusLabel.Text = "Opening " & SerialPort2.PortName
                Application.DoEvents()
                On Error GoTo Open_Error
                InData2 = ""
                SerialPort2.Open()
                ButtonConnect2.Text = "Disconnect 2"
                ComboBoxCom2.Enabled = False
                StatusLabel.Text = "Connected " & SerialPort2.PortName
                LogScope("Status = ", Color.Black, StatusLabel.Text & " (COM port2)")
                TimerSerial2BufferCheck.Enabled = True
            Else
                TimerSerial2BufferCheck.Enabled = False
                SerialPort2.Close()
                ButtonConnect2.Text = "Connect 2"
                ComboBoxCom2.Enabled = True
                StatusLabel.Text = "Disconnected " & SerialPort2.PortName
                LogScope("Status = ", Color.Black, StatusLabel.Text & " (COM port2)")
            End If
        End If

        Exit Sub

Open_Error:
        StatusLabel.Text = Err.Description
        LogScope("Status = ", Color.DarkRed, StatusLabel.Text)

    End Sub

    Private Sub ExitToolStripMenuItem_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Dim S As String = ""

        S = MessageBox.Show("Save settings?", "AP GTO Mini Control", _
              MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
        Select Case S
            Case vbYes
                If Form_Dome.Visible = True Then
                    Form_Dome.CloseDome()
                    Form_Dome.Close()
                End If
                SaveSettings()
                CloseForms()

                ' exit program
                If SerialPort1.IsOpen = True Then SerialPort1.Close()
                If SocketIsOpen = True Then tcpClient.Close()
                If IsConnected = True Then
                    driver.Connected = False
                    driver.Dispose()
                End If
                ExitButtonPressed = True
                Application.Exit()

            Case vbNo
                If SerialPort1.IsOpen = True Then SerialPort1.Close()
                If SocketIsOpen = True Then tcpClient.Close()
                If IsConnected = True Then
                    driver.Connected = False
                    driver.Dispose()
                End If
                If Form_Dome.Visible = True Then
                    Form_Dome.CloseDome()
                End If
                CloseForms()
                ExitButtonPressed = True
                Application.Exit()

            Case vbCancel
        End Select

    End Sub

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If AutoDomeTrackStartup.Checked = True And Form_Dome.CheckBoxTrack.Checked = True Then
            Talker.Speak("Automatic dome tracking shutting down")
        End If
        If ExitButtonPressed = False Then
            SaveSettings()
        End If
        CloseForms()

    End Sub

    Private Sub CloseForms()
        ' close any other forms so they will save position
        Form_DATE_TIME.Close()
        Form_RA_DEC.Close()
        Form_FOCUS.Close()
        Form_SEARCH.Close()
        Form_SYNC.Close()
        Form_Dome.Close()
        Form_DomeHelp.Close()
        Form_DATE_TIME.Close()
        Form_DIAGS.Close()
        Form_DOME_SENT_RESP_LOG.Close()
        Form_SENT_RESP_LOG.Close()
        Form_Monitor.Close()
        Form_Save_Restore.Close()
        Form_TrackingRate.Close()
        Form_COM_PORTS.Close()
        Form_FocusAGF.Close()
        Form_FocusML.Close()
        Form_Meridian.Close()
        Form_ControlP.Close()
        Form_Msg.Close()
        Form_FocusASCOM2.Close()
        Form_FocusHelp.Close()
        Form_KeysHelp.Close()

    End Sub

    Public Sub SaveSettings()
        If Me.WindowState <> FormWindowState.Normal Then
            Me.WindowState = FormWindowState.Normal
        End If

        ' save ap log form height and width
        If Form_SENT_RESP_LOG.Visible = True Then
            Form_SENT_RESP_LOG.CloseToolStripMenuItem.PerformClick()
        End If
        My.Settings.LogWidth = LogW
        My.Settings.LogHeight = LogH

        ' save command log if option set
        Dim SaveCommandLog As Boolean = Form_SENT_RESP_LOG.CheckBoxSaveExit.Checked
        My.Settings.SaveCommandLogExit = SaveCommandLog
        If SaveCommandLog = True Then
            Dim LogFile As String
            Dim DateTime As String = Now.Year & "-" _
                & Format(Now.Month, "00") & "-" & Format(Now.Day, "00") _
                & "_" & Format(Now.Hour, "00") & Format(Now.Minute, "00") & Format(Now.Second, "00")
            LogFile = LogsFolder & "\AP-Mini_Command_Log " & DateTime & ".rtf"
            LogFile = LogFile.Replace("/", "-")
            Try
                File.WriteAllText(LogFile, Form_SENT_RESP_LOG.RichTextBox1.Rtf)
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error Saving Command Log")
                LogSaveError = True
            End Try
        End If

        ' save dome form height and width
        If Form_Dome.Visible = True Then
            Form_Dome.ButtonClose.PerformClick()
        End If
        My.Settings.DomeWidth = DomeW
        My.Settings.DomeHeight = DomeH

        ' save dome log form height and width
        If Form_DOME_SENT_RESP_LOG.Visible = True Then
            Form_DOME_SENT_RESP_LOG.CloseToolStripMenuItem.PerformClick()
        End If
        My.Settings.DomeLogWidth = DomeLogW
        My.Settings.DomeLogHeight = DomeLogH

        ' save dome command log if option set
        Dim SaveDomeLog As Boolean = Form_DOME_SENT_RESP_LOG.CheckBoxSaveExit.Checked
        My.Settings.SaveDomeLogExit = SaveDomeLog
        If LogSaveError = False Then
            If SaveDomeLog = True Then
                Dim LogFile As String
                Dim DateTime As String = Now.Year & "-" _
                    & Format(Now.Month, "00") & "-" & Format(Now.Day, "00") _
                    & "_" & Format(Now.Hour, "00") & Format(Now.Minute, "00") & Format(Now.Second, "00")
                LogFile = LogsFolder & "\AP-Mini_Dome_Log " & DateTime & ".rtf"
                LogFile = LogFile.Replace("/", "-")
                Try
                    File.WriteAllText(LogFile, Form_DOME_SENT_RESP_LOG.RichTextBox1.Rtf)
                Catch ex As Exception
                    MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Error Saving Dome Command Log")
                    LogSaveError = True
                End Try
            End If
        End If

        ' save monitor window size
        If Form_Monitor.Visible = True Then
            Form_Monitor.Close()
        End If
        My.Settings.MonitorWidth = MonitorW
        My.Settings.MonitorHeight = MonitorH

        ' save save/restore window size
        If Form_Save_Restore.Visible = True Then
            Form_Save_Restore.Close()
        End If
        My.Settings.SaveRestoreWidth = SaveRestoreW
        My.Settings.SaveRestoreHeight = SaveRestoreH

        ' save focus agf window size
        If Form_FocusAGF.Visible = True Then
            Form_FocusAGF.ButtonClose.PerformClick()
        End If
        My.Settings.FocusAgfWidth = FocusAgfW
        My.Settings.FocusAgfHeight = FocusAgfH

        ' save focus moonlite window size
        If Form_FocusML.Visible = True Then
            Form_FocusML.ButtonClose.PerformClick()
        End If
        My.Settings.FocusMlWidth = FocusMlW
        My.Settings.FocusMlHeight = FocusMlH

        ' save Window postion
        My.Settings.PosLeft = Me.Left
        My.Settings.PosTop = Me.Top

        ' save Window size
        My.Settings.SizeHeight = Me.Height
        My.Settings.SizeWidth = Me.Width

        ' save com port
        My.Settings.ComPort = ToolStripComboBoxCom.Items(ToolStripComboBoxCom.SelectedIndex)

        ' save com port2 (focus commands)
        My.Settings.ComPort2 = ComboBoxCom2.Items(ComboBoxCom2.SelectedIndex)

        ' save com port AGF
        If Form_Dome.ComboBoxAGF.SelectedIndex >= 0 Then
            My.Settings.ComPortAGF = Form_Dome.ComboBoxAGF.Items(Form_Dome.ComboBoxAGF.SelectedIndex)
        End If

        ' save com port AGF dsr
        If Form_Dome.ComboboxAGFdsrCom.SelectedIndex >= 0 Then
            My.Settings.ComPortAGFdsr = Form_Dome.ComboboxAGFdsrCom.Items(Form_Dome.ComboboxAGFdsrCom.SelectedIndex)
        End If

        ' save com port AGF debug
        If Form_Dome.ComboBoxAGFdebugCom.SelectedIndex >= 0 Then
            My.Settings.ComPortAGFdebug = Form_Dome.ComboBoxAGFdebugCom.Items(Form_Dome.ComboBoxAGFdebugCom.SelectedIndex)
        End If

        ' save com port AGF focus box
        If Form_FocusAGF.ToolStripComboBoxCom.SelectedIndex >= 0 Then
            My.Settings.ComPortFocusAGF = Form_FocusAGF.ToolStripComboBoxCom.Items(Form_FocusAGF.ToolStripComboBoxCom.SelectedIndex)
        End If

        ' save com port MoonLite stepper motor
        If Form_FocusML.ToolStripComboBoxCom.SelectedIndex >= 0 Then
            My.Settings.ComPortFocusML = Form_FocusML.ToolStripComboBoxCom.Items(Form_FocusML.ToolStripComboBoxCom.SelectedIndex)
        End If

        ' save slew time ms
        My.Settings.SlewMs = NumericUpDownSlew.Value

        ' save focus time ms
        My.Settings.FocusMs = Form_FOCUS.NumericUpDownFocus.Value

        ' save timed slew check
        My.Settings.TimedSlew = CheckBoxSlewTime.Checked

        ' save timed focus check
        My.Settings.TimedFocus = Form_FOCUS.CheckBoxFocusTime.Checked

        ' save search direction time and delay ms
        My.Settings.SearchMs = Form_SEARCH.SlewMs.Value
        My.Settings.SearchDelay = Form_SEARCH.DelayMS.Value

        ' save variable slew and centering rates
        My.Settings.VarCenter = NumericUpDownRateC.Value
        My.Settings.VarSlew = NumericUpDownRate.Value

        ' save dome controler network
        My.Settings.DomeNet = Form_Dome.DomeTest
        My.Settings.DomeIP = Form_Dome.RemoteIP
        My.Settings.DomeLocateNet = Form_Dome.ToolStripTextBoxMask.Text
        My.Settings.DomeSetIP = Form_Dome.ToolStripTextBoxIP.Text

        ' save AGF absolute encoder
        My.Settings.AGFencoder = Form_Dome.ButtonAGFencoder.Checked

        ' dome controler window state
        If Form_Dome.Visible = True Then
            If Form_Dome.WindowState <> FormWindowState.Normal Then
                Form_Dome.WindowState = FormWindowState.Normal
            End If
        End If

        ' save diag values
        My.Settings.DiagRun = Form_DIAGS.NumericUpDownRun.Value
        My.Settings.DiagDelay = Form_DIAGS.NumericUpDownDelay.Value

        ' save other forms positions
        My.Settings.PosTopS = PosTopS
        My.Settings.PosLeftS = PosLeftS
        My.Settings.PosTopReCal = PosTopReCal
        My.Settings.PoslLeftReCal = PosLeftReCal

        ' save always on top setting
        My.Settings.TopAlways = Form_ControlP.CheckBoxAlwaysOnTop.Checked

        ' save timed beep
        My.Settings.TimedBeep = Form_ControlP.CheckBoxTimedBeep.Checked

        ' save button directions
        My.Settings.NSbuttons = CheckBoxFlipNS.Checked
        My.Settings.EWbuttons = CheckBoxFlipEW.Checked

        ' save button active color
        My.Settings.MiniActivateColor = ActiveColor

        ' save web form height and width
        My.Settings.WebWidth = WebW
        My.Settings.WebHeight = WebH

        ' save web browser type
        My.Settings.InternalWebBrowser = Form_Dome.InternalWebToolStripMenuItem.Checked

        ' save dome track interval
        My.Settings.TrackInterval = Form_Dome.NumericUpDownTrack.Value

        ' save dome sync degrees
        My.Settings.DomeMoveDegAGF = Form_Dome.NumericUpDownSyncDeg.Value

        ' save dome settings
        My.Settings.DomeSettings = DomeCurrent
        My.Settings.DomeTab = Form_Dome.TabControl1.SelectedIndex

        ' save control settings tab
        My.Settings.ControlPtab = Form_ControlP.TabControlP.SelectedIndex

        ' save dome AGF move deg. / sec.
        My.Settings.DomeDegSecAGF = Form_Dome.MaskedTextBoxDegSec.Text

        ' save stop dome tracking on timeout option
        My.Settings.StopDomeTrackingOnTimeout = Form_Dome.StopTrackingOnTimeout.Checked

        ' last dome position
        My.Settings.LastDomePos = Form_Dome.TrackBarDomePos.Value

        ' save error message box setting
        My.Settings.ErrorMsgBox = Form_ControlP.CheckBoxErrorMsgBox.Checked

        ' save domes file (blank if using default)
        My.Settings.DomesFile = DomesFileCustom

        ' save 1st command delay
        My.Settings.Delay1stCmd = Form_ControlP.CheckBoxDelay1stCommand.Checked
        My.Settings.Delay1stCmdTime = Form_ControlP.NumUpDownDelay1.Value

        ' save auto dome track on startup
        My.Settings.StartAutoDomeTrack = AutoDomeTrackStartup.Checked

        ' save read timeout
        My.Settings.ReadTimeout = ReadTimeout

        ' save manual dsr switch
        My.Settings.TrackingDSR = Form_Dome.ConnectDSRport.Checked

        ' save debug logging option
        My.Settings.DebugLogging = Form_Dome.DebugLogging.Checked

        ' save part dome position
        My.Settings.Parkdome = Form_Dome.ComboBoxDomePark.SelectedIndex

        ' save duration timer will park dome
        My.Settings.DurTimerParkDome = Form_Dome.DurTimerParksDome.Checked

        ' save stop PHD 
        My.Settings.StopPHD = StopPHD
        My.Settings.PHDname = Form_ControlP.TextBoxPHDname.Text

        ' save duration timer park position
        Dim P As Integer = 0
        If Form_ControlP.CheckBoxPark1.Checked = True Then
            P = 1
        End If
        If Form_ControlP.CheckBoxPark2.Checked = True Then
            P = 2
        End If
        If Form_ControlP.CheckBoxPark3.Checked = True Then
            P = 3
        End If
        If Form_ControlP.CheckBoxPark4.Checked = True Then
            P = 4
        End If
        My.Settings.DurTimerParkPos = P

        ' save meridian stop check box
        My.Settings.StopMer = Form_ControlP.CheckBoxStopMeridian.Checked

        ' save stop tracking and park time check box
        My.Settings.StopDur = Form_ControlP.CheckBoxStopDur.Checked

        ' save dome log no duplicate entries
        My.Settings.DomeLogNoDups = Form_Dome.NoDupStatusEntries.Checked

        ' save speak rate
        My.Settings.SpeakRate = Form_ControlP.ComboBoxSpeakRate.SelectedIndex

        ' save stop tracking numbers
        My.Settings.StopTrackingDur = Form_ControlP.TextBoxStopDur.Text
        My.Settings.StopTrackingDeg = Form_ControlP.NumericUpDownStopDeg.Value
        My.Settings.StopTrackingAlt = Form_ControlP.NumericUpDownStopAlt.Value

        ' save stop tracking check boxes
        My.Settings.StopTrackingCheckMer = Form_ControlP.CheckBoxStopMeridian.Checked
        My.Settings.StopTrackingCheckDur = Form_ControlP.CheckBoxStopDur.Checked
        My.Settings.StopTrackingCheckAlt = Form_ControlP.CheckBoxStopAlt.Checked

        ' save show status window on startup option
        My.Settings.ShowStatusOnStartup = Form_ControlP.CheckBoxPosWinStartup.Checked

        ' save save restore filename
        My.Settings.SaveRestoreFile = SaveRestoreFilename

        ' save tracking rates
        If Form_TrackingRate.Visible = True Then
            Form_TrackingRate.WindowState = FormWindowState.Normal
            Form_TrackingRate.Close()
        End If
        My.Settings.RArate = RArate
        My.Settings.TrackingRAinc = RArateInc
        My.Settings.DECrate = DECrate
        My.Settings.TrackingDECinc = DECrateInc
        My.Settings.TrackingRateFile = TrackingRateFilename
        My.Settings.RAdrift = RAdrift
        My.Settings.DECdrift = DECdrift
        My.Settings.RAdriftHMS = RAdriftHMS
        My.Settings.DECdriftHMS = DECdriftHMS
        My.Settings.AdjustdRA = AdjustdRA

        ' save park 4 positions
        My.Settings.Park4_AL = AP_AL_Park4
        My.Settings.Park4_AZ = AP_AZ_Park4

        ' save EW switch function
        My.Settings.MeridianSwitchCP3 = EWswitchCP3MeridianDelay

        ' com port2 adjust ra/dec from J2000 to current JD
        My.Settings.ComPort2AdjRaDecJD = ToolStripMenuItemRDadjust.Checked

        ' save last ra/dec if not null
        If SavedRaFull <> "" Then
            My.Settings.LastRaPos = SavedRaFull
        End If
        If SavedDecFull <> "" Then
            My.Settings.LastDecPos = SavedDecFull
        End If

        ' save start tracking on connect option
        My.Settings.StartOnConnect = StartOnConnect

        ' save stop tracking on connect option
        My.Settings.StopOnConnect = StopOnConnect

        ' save stop tracking on park option
        My.Settings.StopOnPark = StopOnPark

        ' save stop tracking on alt/az slew option
        My.Settings.StopOnAltAzSlew = StopOnAltAzSlew

        ' save AGF Dome Controller network address
        My.Settings.AGFipAddress = Form_Dome.AGFipAddress

        ' save AP mount network address
        My.Settings.APipAddress = APipAddress

        ' save AP mount network address
        My.Settings.APipPort = APipPort

        ' save AP mount network purge timeout
        My.Settings.APipPurgeTimeout = APipPurgeTimeout

        ' save Xport power box ip address
        My.Settings.XportIP = XPORTipAddress

        ' save Xport power box ip port
        My.Settings.XportPort = XPORTipPort

        ' debug logging main window
        My.Settings.DebugLoggingMain = Form_ControlP.CheckBoxDebugLogging.Checked

        ' agf dome position
        My.Settings.DomeLastPos = Form_Dome.TrackBarDomePos.Value

        ' agf focus box timed options
        My.Settings.FocusAgfTimed = Form_FocusAGF.CheckBoxFocusTime.Checked
        My.Settings.FocusAgfTimems = Form_FocusAGF.NumericUpDownFocus.Value
        My.Settings.FocusAgfTimed2 = Form_FocusAGF.CheckBoxfocusTime2.Checked
        My.Settings.FocusAgfTimems2 = Form_FocusAGF.NumericUpDownFocus2.Value
        My.Settings.FocusAgfMotor = Form_FocusAGF.TabControl1.SelectedIndex
        My.Settings.FocusAgfRev1 = Form_FocusAGF.CheckBoxRev1.Checked
        My.Settings.FocusAgfRev2 = Form_FocusAGF.CheckBoxRev2.Checked
        My.Settings.FocusAgfShowCmds = Form_FocusAGF.ShowCommandsSentToolStripMenuItem.Checked

        ' moonlite stepper motor focuser options
        My.Settings.FocusMlShowCmds = Form_FocusML.ShowCommandsSent.Checked
        My.Settings.FocusMlInc1 = Form_FocusML.ComboBoxInc1.SelectedIndex
        My.Settings.FocusMlInc2 = Form_FocusML.ComboBoxInc2.SelectedIndex
        My.Settings.FocusMlSpeed1 = Form_FocusML.ComboBoxMotorSpeed1.SelectedIndex
        My.Settings.FocusMlSpeed2 = Form_FocusML.ComboBoxMotorSpeed2.SelectedIndex
        My.Settings.FocusMlLedBacklight = Form_FocusML.ComboBoxRedBacklight.SelectedIndex
        My.Settings.FocusMlMotor = Form_FocusML.TabControl1.SelectedIndex
        My.Settings.MoonliteDualController = Form_FocusML.DualMotorController.Checked


        ' meridian offset
        Form_Meridian.SaveMeridianOffset()
        My.Settings.MeridianOffset = MeridianOffset

        ' save meridian offset on connect
        My.Settings.SetMeridianOffsetOnConnect = SetMeridianOffsetOnConnect

        ' save power relay settings
        My.Settings.PwrRelay1 = PwrRelay1
        My.Settings.PwrRelay2 = PwrRelay2
        My.Settings.PwrRelay2 = PwrRelay3
        My.Settings.PwrRelay1Name = PwrRelay1Name
        My.Settings.PwrRelay2Name = PwrRelay2Name
        My.Settings.PwrRelay3Name = PwrRelay3Name
        My.Settings.DurTimerPwrOff = DurTimerPwrOff

        ' save duration timer disconnect setting
        My.Settings.DurTimerDisconnect = DurTimerDisconnect

        ' save meridian timer will park setting
        My.Settings.MerTimerPark = MerTimerPark

        ' save duration timer will park setting
        My.Settings.DurTimerPark = DurTimerPark

        ' save altitude timer will park setting
        My.Settings.AltTimerPark = AltTimerPark

        ' save control dome test values
        My.Settings.DomeTestDeg = Form_ControlP.NumDegs.Value
        My.Settings.DomeTestWait = Form_ControlP.NumWait.Value
        My.Settings.DomeTestLoop = Form_ControlP.NumLoop.Value
        If Form_ControlP.DirCW.Checked = True Then
            My.Settings.DomeTestDir = "CW"
        End If
        If Form_ControlP.DirCCW.Checked = True Then
            My.Settings.DomeTestDir = "CCW"
        End If
        My.Settings.DomeDiagToggle = Form_ControlP.CheckBoxToggle.Checked

        ' save focuser type
        My.Settings.Focuser = ComboBoxFocuser.SelectedIndex

        ' save ASCOM focuser #1 values
        If Form_FocusASCOM2.Visible = True Then
            Form_FocusASCOM2.ButtonClose.PerformClick()
        End If
        My.Settings.MoveSize = MoveSize
        My.Settings.IncDecSize = IncDecSize
        My.Settings.FocusASCOMid = FocusASCOMid
        My.Settings.FocuserASCOMname = FocuserASCOMname

        ' save ASCOM focuser #2 values
        My.Settings.MoveSize2 = MoveSize2
        My.Settings.IncDecSize2 = IncDecSize2
        My.Settings.FocusASCOMid2 = FocusASCOMid2
        My.Settings.FocuserASCOMname2 = FocuserASCOMname2

        ' save ASCOM focus motor
        My.Settings.FocusASCOMmotor = Form_FocusASCOM2.TabControl1.SelectedIndex

        ' save AGF dome wheel bias 
        My.Settings.AGFbias = Form_Dome.TextBoxDomeWheelBias.Text

        ' save AGF emulator mode
        My.Settings.AGFemulator = Form_Dome.AGFdomeEmulatorMode.Checked

        ' save logs save folder
        My.Settings.LogsFolder = LogsFolder

        ' set upgrade setting not needed
        My.Settings.NeedUpgrade = False

        My.Settings.Save()

    End Sub

    Private Sub StopAny()
        If TimerN.Enabled = True Or TimerS.Enabled = True Or TimerE.Enabled = True Or TimerW.Enabled = True Then
            ButtonSlewStop.PerformClick()
        End If
        If TimerAltStopDeg.Enabled = True Or TimerO.Enabled = True Then
            Form_FOCUS.ButtonFocusStop.PerformClick()
        End If
    End Sub

    Public Sub SetSlewRate(ByVal index As Integer)
        If SerialPort1.IsOpen = True Or SocketIsOpen = True Or IsConnected = True Then
            SlewRateIndex = index
            Select Case index
                Case 1
                    Slew_Rate = "0.25x"
                    Slew_Cmd = ":RG0#"
                    LabelSlewRate25.BackColor = RateActiveColor
                    LabelSlewRate50.BackColor = RateInactiveColor
                    LabelSlewRate10.BackColor = RateInactiveColor
                    LabelSlewRate12.BackColor = RateInactiveColor
                    LabelSlewRate64.BackColor = RateInactiveColor
                    LabelSlewRate600.BackColor = RateInactiveColor
                    LabelCenterRateVar.BackColor = RateInactiveColor
                Case 2
                    Slew_Rate = "0.5x"
                    Slew_Cmd = ":RG1#"
                    LabelSlewRate25.BackColor = RateInactiveColor
                    LabelSlewRate50.BackColor = RateActiveColor
                    LabelSlewRate10.BackColor = RateInactiveColor
                    LabelSlewRate12.BackColor = RateInactiveColor
                    LabelSlewRate64.BackColor = RateInactiveColor
                    LabelSlewRate600.BackColor = RateInactiveColor
                    LabelCenterRateVar.BackColor = RateInactiveColor
                Case 3
                    Slew_Rate = "1.0x"
                    Slew_Cmd = ":RG2#"
                    LabelSlewRate25.BackColor = RateInactiveColor
                    LabelSlewRate50.BackColor = RateInactiveColor
                    LabelSlewRate10.BackColor = RateActiveColor
                    LabelSlewRate12.BackColor = RateInactiveColor
                    LabelSlewRate64.BackColor = RateInactiveColor
                    LabelSlewRate600.BackColor = RateInactiveColor
                    LabelCenterRateVar.BackColor = RateInactiveColor
                Case 4
                    Slew_Rate = "12x"
                    Slew_Cmd = ":RC0#"
                    LabelSlewRate25.BackColor = RateInactiveColor
                    LabelSlewRate50.BackColor = RateInactiveColor
                    LabelSlewRate10.BackColor = RateInactiveColor
                    LabelSlewRate12.BackColor = RateActiveColor
                    LabelSlewRate64.BackColor = RateInactiveColor
                    LabelSlewRate600.BackColor = RateInactiveColor
                    LabelCenterRateVar.BackColor = RateInactiveColor
                Case 5
                    Slew_Rate = "64x"
                    Slew_Cmd = ":RC1#"
                    LabelSlewRate25.BackColor = RateInactiveColor
                    LabelSlewRate50.BackColor = RateInactiveColor
                    LabelSlewRate10.BackColor = RateInactiveColor
                    LabelSlewRate12.BackColor = RateInactiveColor
                    LabelSlewRate64.BackColor = RateActiveColor
                    LabelSlewRate600.BackColor = RateInactiveColor
                    LabelCenterRateVar.BackColor = RateInactiveColor
                Case 6
                    Slew_Rate = "600x"
                    Slew_Cmd = ":RC2#"
                    LabelSlewRate25.BackColor = RateInactiveColor
                    LabelSlewRate50.BackColor = RateInactiveColor
                    LabelSlewRate10.BackColor = RateInactiveColor
                    LabelSlewRate12.BackColor = RateInactiveColor
                    LabelSlewRate64.BackColor = RateInactiveColor
                    LabelSlewRate600.BackColor = RateActiveColor
                    LabelCenterRateVar.BackColor = RateInactiveColor
            End Select
            Cmd = Slew_Cmd
            CurrentRate = Slew_Cmd
            SendReceiveAP(Cmd, "Button Rate", False, 0)
            StatusLabel.Text = "Button rate set to " & Slew_Rate
        End If

    End Sub

    Private Sub LabelSlewRate25_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LabelSlewRate25.Click
        SetSlewRate(1)
        SHC1 = RateActiveColor

    End Sub

    Private Sub LabelSlewRate50_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LabelSlewRate50.Click
        SetSlewRate(2)
        SHC2 = RateActiveColor

    End Sub

    Public Sub LabelSlewRate10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LabelSlewRate10.Click
        SetSlewRate(3)
        SHC3 = RateActiveColor

    End Sub

    Private Sub LabelSlewRate12_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LabelSlewRate12.Click
        SetSlewRate(4)
        SHC4 = RateActiveColor

    End Sub

    Private Sub LabelSlewRate64_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LabelSlewRate64.Click
        SetSlewRate(5)
        SHC5 = RateActiveColor

    End Sub

    Private Sub LabelSlewRate600_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LabelSlewRate600.Click
        SetSlewRate(6)
        SHC6 = RateActiveColor

    End Sub

    Private Sub LabelCenterRateVar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LabelCenterRateVar.Click
        SetVarCenterRate()
        SHC7 = RateActiveColor

    End Sub

    Public Sub SetVarCenterRate()
        Slew_Rate = NumericUpDownRateC.Value & "x"
        Slew_Cmd = ":Rc" & Format(NumericUpDownRateC.Value, "000") & "#"
        LabelCenterRateVar.BackColor = RateActiveColor
        CurrentRate = Slew_Cmd
        Cmd = Slew_Cmd
        SendReceiveAP(Cmd, "Var. Center Rate", False, 0)
        StatusLabel.Text = "GTOCP3 centering rate set to " & Slew_Rate
        LabelSlewRate25.BackColor = RateInactiveColor
        LabelSlewRate50.BackColor = RateInactiveColor
        LabelSlewRate10.BackColor = RateInactiveColor
        LabelSlewRate12.BackColor = RateInactiveColor
        LabelSlewRate64.BackColor = RateInactiveColor
        LabelSlewRate600.BackColor = RateInactiveColor

    End Sub

    Private Sub LabelSlewRateVar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LabelSlewRateVar.Click
        Slew_Rate = NumericUpDownRate.Value & "x"
        Cmd = ":Rs" & Format(NumericUpDownRate.Value, "0000") & "#"
        LabelSlewRateVar.BackColor = RateActiveColor
        SendReceiveAP(Cmd, "Var. Slew Rate", False, 0)
        StatusLabel.Text = "GTOCP3 slew rate set to " & Slew_Rate

    End Sub

    Public Sub ButtonSlewStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSlewStop.Click
        TimerN.Enabled = False
        TimerS.Enabled = False
        TimerE.Enabled = False
        TimerW.Enabled = False
        TimerProgN.Enabled = False
        TimerProgS.Enabled = False
        TimerProgE.Enabled = False
        TimerProgW.Enabled = False
        AP_Command("Stop")

    End Sub

    Public Sub UpdateNScount()
        If NorthSouthCount < 0 Then
            TextBoxNScount.Text = NorthSouthCount & " S"
        Else
            TextBoxNScount.Text = NorthSouthCount & " N"
        End If

    End Sub

    Public Sub UpdateEWcount()
        If EastWestCount < 0 Then
            TextBoxEWcount.Text = EastWestCount & " W"
        Else
            TextBoxEWcount.Text = EastWestCount & " E"
        End If

    End Sub

    Public Sub ButtonN_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonN.Click
        If CheckBoxSlewTime.Checked = True Then
            SlewTime = NumericUpDownSlew.Value
            If CheckBoxFlipNS.Checked = False Then
                NSrealCount = NorthSouthCount + SlewTime
            Else
                NSrealCount = NorthSouthCount - SlewTime
            End If
            AP_Command("N")
            TimerN.Interval = SlewTime
            TimerN.Enabled = True
            TimerS.Enabled = False
            ProgN = (SlewTime / TimerProgN.Interval) - 1
            TimerProgN.Enabled = True
        End If

    End Sub

    Public Sub ButtonS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonS.Click
        If CheckBoxSlewTime.Checked = True Then
            SlewTime = NumericUpDownSlew.Value
            If CheckBoxFlipNS.Checked = False Then
                NSrealCount = NorthSouthCount - SlewTime
            Else
                NSrealCount = NorthSouthCount + SlewTime
            End If
            AP_Command("S")
            TimerS.Interval = SlewTime
            TimerS.Enabled = True
            TimerN.Enabled = False
            ProgS = (SlewTime / TimerProgS.Interval) - 1
            TimerProgS.Enabled = True
        End If

    End Sub

    Public Sub ButtonE_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonE.Click
        If CheckBoxSlewTime.Checked = True Then
            SlewTime = NumericUpDownSlew.Value
            If CheckBoxFlipEW.Checked = False Then
                EWrealCount = EastWestCount + SlewTime
            Else
                EWrealCount = EastWestCount - SlewTime
            End If
            AP_Command("E")
            TimerE.Interval = SlewTime
            TimerE.Enabled = True
            TimerW.Enabled = False
            ProgE = (SlewTime / TimerProgE.Interval) - 1
            TimerProgE.Enabled = True
        End If

    End Sub

    Public Sub ButtonW_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonW.Click
        If CheckBoxSlewTime.Checked = True Then
            SlewTime = NumericUpDownSlew.Value
            If CheckBoxFlipEW.Checked = False Then
                EWrealCount = EastWestCount - SlewTime
            Else
                EWrealCount = EastWestCount + SlewTime
            End If
            AP_Command("W")
            TimerW.Interval = SlewTime
            TimerW.Enabled = True
            TimerE.Enabled = False
            ProgW = (SlewTime / TimerProgW.Interval) - 1
            TimerProgW.Enabled = True
        End If

    End Sub

    Private Sub ButtonN_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ButtonN.MouseDown
        If CheckBoxSlewTime.Checked = False Then
            ProgNstart()
        End If

    End Sub

    Private Sub ButtonN_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ButtonN.MouseUp
        If CheckBoxSlewTime.Checked = False Then
            ProgNend()
        End If

    End Sub

    Private Sub ButtonS_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ButtonS.MouseDown
        If CheckBoxSlewTime.Checked = False Then
            ProgSstart()
        End If

    End Sub

    Private Sub ButtonS_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ButtonS.MouseUp
        If CheckBoxSlewTime.Checked = False Then
            progSend()
        End If

    End Sub

    Private Sub ButtonE_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ButtonE.MouseDown
        If CheckBoxSlewTime.Checked = False Then
            ProgEstart()
        End If

    End Sub

    Private Sub ButtonE_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ButtonE.MouseUp
        If CheckBoxSlewTime.Checked = False Then
            progEend()
        End If

    End Sub

    Private Sub ButtonW_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ButtonW.MouseDown
        If CheckBoxSlewTime.Checked = False Then
            ProgWstart()
        End If

    End Sub

    Private Sub ButtonW_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ButtonW.MouseUp
        If CheckBoxSlewTime.Checked = False Then
            progWend()
        End If

    End Sub

    Public Sub ProgNstart()
        AP_Command("N")
        TimeStart = Microsoft.VisualBasic.DateAndTime.Timer
        NSrealCount = NorthSouthCount
        ProgN = 1000000
        TimerProgN.Enabled = True

    End Sub

    Public Sub ProgNend()
        AP_Command("StopN")
        TimeEnd = Microsoft.VisualBasic.DateAndTime.Timer
        If CheckBoxFlipNS.Checked = False Then
            NorthSouthCount = NSrealCount + (1000 * (TimeEnd - TimeStart))
        Else
            NorthSouthCount = NSrealCount - (1000 * (TimeEnd - TimeStart))
        End If
        TimerProgN.Enabled = False
        UpdateNScount()

    End Sub

    Public Sub ProgSstart()
        AP_Command("S")
        TimeStart = Microsoft.VisualBasic.DateAndTime.Timer
        NSrealCount = NorthSouthCount
        ProgS = 1000000
        TimerProgS.Enabled = True

    End Sub

    Public Sub progSend()
        AP_Command("StopS")
        TimeEnd = Microsoft.VisualBasic.DateAndTime.Timer
        If CheckBoxFlipNS.Checked = False Then
            NorthSouthCount = NSrealCount - (1000 * (TimeEnd - TimeStart))
        Else
            NorthSouthCount = NSrealCount + (1000 * (TimeEnd - TimeStart))
        End If
        TimerProgS.Enabled = False
        UpdateNScount()

    End Sub

    Public Sub ProgEstart()
        AP_Command("E")
        TimeStart = Microsoft.VisualBasic.DateAndTime.Timer
        EWrealCount = EastWestCount
        ProgE = 1000000
        TimerProgE.Enabled = True

    End Sub

    Public Sub progEend()
        AP_Command("StopE")
        TimeEnd = Microsoft.VisualBasic.DateAndTime.Timer
        If CheckBoxFlipEW.Checked = False Then
            EastWestCount = EWrealCount + (1000 * (TimeEnd - TimeStart))
        Else
            EastWestCount = EWrealCount - (1000 * (TimeEnd - TimeStart))
        End If
        TimerProgE.Enabled = False
        UpdateEWcount()

    End Sub

    Public Sub ProgWstart()
        AP_Command("W")
        TimeStart = Microsoft.VisualBasic.DateAndTime.Timer
        EWrealCount = EastWestCount
        ProgW = 1000000
        TimerProgW.Enabled = True

    End Sub

    Public Sub progWend()
        AP_Command("StopW")
        TimeEnd = Microsoft.VisualBasic.DateAndTime.Timer
        If CheckBoxFlipEW.Checked = False Then
            EastWestCount = EWrealCount - (1000 * (TimeEnd - TimeStart))
        Else
            EastWestCount = EWrealCount + (1000 * (TimeEnd - TimeStart))
        End If
        TimerProgW.Enabled = False
        UpdateEWcount()

    End Sub

    Private Sub KeyControl_GotFocus(sender As Object, e As System.EventArgs) Handles KeyControl.GotFocus
        KeyControl.BackColor = ActiveColor
        Form_FOCUS.ButtonKeyboard.BackColor = ActiveColor
        LabelKey.Visible = True

    End Sub

    Private Sub KeyControl_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles KeyControl.LostFocus
        KeyControl.BackColor = Color.Transparent
        Form_FOCUS.ButtonKeyboard.BackColor = Color.Transparent
        LabelKey.Visible = False

    End Sub

    Private Sub KeyControl_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles KeyControl.KeyDown
        Dim K As String

        If IgnoreKey = False Then
            If KeyHeld = False Then
                K = e.KeyCode
                If K = Keys.Menu Then
                    IgnoreKey = True
                Else
                    IgnoreKey = False
                    If CheckBoxSlewTime.Checked = False Then
                        Select Case K
                            Case Keys.Down, Keys.NumPad2
                                ProgSstart()
                            Case Keys.Up, Keys.NumPad5
                                ProgNstart()
                            Case Keys.Right, Keys.NumPad3
                                ProgEstart()
                            Case Keys.Left, Keys.NumPad1
                                ProgWstart()
                        End Select
                    End If
                    If Form_FOCUS.CheckBoxFocusTime.Checked = False Then
                        Select Case K
                            Case Keys.PageUp, Keys.NumPad4, Keys.OemOpenBrackets
                                Form_FOCUS.ProgIstart()
                            Case Keys.PageDown, Keys.NumPad6, Keys.OemCloseBrackets
                                Form_FOCUS.ProgOstart()
                        End Select
                    End If
                    KeyHeld = True
                    startDate = Now
                End If
            End If
        End If

    End Sub

    Private Sub KeyControl_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles KeyControl.KeyUp
        Dim K As String = ""

        K = e.KeyCode
        If IgnoreKey = False Then
            If Form_ControlP.CheckBoxDebugLogging.Checked = True Then
                LogScope("KeyUp = ", Color.SaddleBrown, K)
            End If
            Select Case K
                Case Keys.Down, Keys.NumPad2
                    If CheckBoxSlewTime.Checked = True Then
                        ButtonS.PerformClick()
                    Else
                        progSend()
                    End If
                Case Keys.Up, Keys.NumPad5
                    If CheckBoxSlewTime.Checked = True Then
                        ButtonN.PerformClick()
                    Else
                        ProgNend()
                    End If
                Case Keys.Right, Keys.NumPad3
                    If CheckBoxSlewTime.Checked = True Then
                        ButtonE.PerformClick()
                    Else
                        progEend()
                    End If
                Case Keys.Left, Keys.NumPad1
                    If CheckBoxSlewTime.Checked = True Then
                        ButtonW.PerformClick()
                    Else
                        progWend()
                    End If

                Case Keys.PageUp, Keys.NumPad4, Keys.OemOpenBrackets
                    If Form_FOCUS.CheckBoxFocusTime.Checked = True Then
                        Form_FOCUS.ButtonFocusIn.PerformClick()
                    Else
                        Form_FOCUS.ProgIend()
                    End If
                Case Keys.PageDown, Keys.NumPad6, Keys.OemCloseBrackets
                    If Form_FOCUS.CheckBoxFocusTime.Checked = True Then
                        Form_FOCUS.ButtonFocusOut.PerformClick()
                    Else
                        Form_FOCUS.ProgOend()
                    End If
                    ' logitech num keypad
                Case Keys.NumPad7, Keys.D7
                    SetSlewRate(3)
                    SHC1 = RateActiveColor
                Case Keys.NumPad8, Keys.D8
                    SetSlewRate(4)
                    SHC2 = RateActiveColor
                Case Keys.NumPad9, Keys.D9
                    SetSlewRate(5)
                    SHC3 = RateActiveColor
                Case Keys.Add, Keys.D0
                    If LabelCenterRateVar.Enabled = True Then
                        SetVarCenterRate()
                    End If
                Case Keys.NumPad0
                    ZeroCounterNS()
                    ZeroCounterEW()
                    Form_FOCUS.ZeroCounterFocus()
                Case Keys.Delete, Keys.D1
                    SaveRD1()
                Case Keys.Divide, Keys.D2
                    SaveRD2()
                Case Keys.Multiply, Keys.D3
                    GotoRD1()
                Case Keys.Subtract, Keys.D4
                    GotoRD2()

                Case Else
                    If CheckBoxSlewTime.Checked = True Then
                        ButtonSlewStop.PerformClick()
                    End If
                    If Form_FOCUS.CheckBoxFocusTime.Checked = True Then
                        Form_FOCUS.ButtonFocusStop.PerformClick()
                    End If
            End Select
            KeyHeld = False
        Else
            If K = Keys.Menu Then
                IgnoreKey = False
            End If
        End If

    End Sub

    Public Sub SaveRD1()
        GetScopeRaDec()
        SaveRA1 = AP_RA
        SaveDEC1 = AP_DEC
        Dim L As String = "Save RA/DEC #1"
        LogScope("Status = ", Color.Black, L)
        StatusLabel.Text = L
        Form_RA_DEC.ButtonGoto1.Enabled = True

    End Sub

    Public Sub SaveRD2()
        GetScopeRaDec()
        SaveRA2 = AP_RA
        SaveDEC2 = AP_DEC
        Dim L As String = "Save RA/DEC #2"
        LogScope("Status = ", Color.Black, L)
        StatusLabel.Text = L
        Form_RA_DEC.ButtonGoto2.Enabled = True

    End Sub

    Public Sub GotoRD1()
        Form_RA_DEC.AP_RA = ":Sr " & SaveRA1
        Form_RA_DEC.AP_DEC = ":Sd " & SaveDEC1
        Form_RA_DEC.GotoRaDec()
        Dim L As String = "Goto RA/DEC #1"
        LogScope("Status = ", Color.Black, L)
        StatusLabel.Text = L

    End Sub

    Public Sub GotoRD2()
        Form_RA_DEC.AP_RA = ":Sr " & SaveRA2
        Form_RA_DEC.AP_DEC = ":Sd " & SaveDEC2
        Form_RA_DEC.GotoRaDec()
        Dim L As String = "Goto RA/DEC #2"
        LogScope("Status = ", Color.Black, L)
        StatusLabel.Text = L

    End Sub

    Public Sub AP_Command(ByVal command As String)
        Dim SendCmd As Boolean
        Dim tickBegin As Long
        Dim tickEnd As Long
        Dim LineColor As Color = Color.Black

        If SerialPort1.IsOpen = False And SocketIsOpen = False And IsConnected = False Then Exit Sub
        SendCmd = True
        Resp = ""
        Cmd = "#"
        AscomRespSent = False
        Select Case command
            Case "N"
                If Slew_Cmd <> "" Then
                    SendReceiveAP(Slew_Cmd, "Button Rate", False, 0)
                End If
                If CheckBoxFlipNS.Checked = False Then
                    Cmd = ":Mn#"
                    Msg = "Slewing North"
                Else
                    Cmd = ":Ms#"
                    Msg = "Slewing South"
                End If
                ButtonN.BackColor = ActiveColor
            Case "S"
                If Slew_Cmd <> "" Then
                    SendReceiveAP(Slew_Cmd, "Button Rate", False, 0)
                End If
                If CheckBoxFlipNS.Checked = False Then
                    Cmd = ":Ms#"
                    Msg = "Slewing South"
                Else
                    Cmd = ":Mn#"
                    Msg = "Slewing North"
                End If
                ButtonS.BackColor = ActiveColor
            Case "E"
                If Slew_Cmd <> "" Then
                    SendReceiveAP(Slew_Cmd, "Button Rate", False, 0)
                End If
                If CheckBoxFlipEW.Checked = False Then
                    Cmd = ":Me#"
                    Msg = "Slewing East"
                Else
                    Cmd = ":Mw#"
                    Msg = "Slewing West"
                End If
                ButtonE.BackColor = ActiveColor
            Case "W"
                If Slew_Cmd <> "" Then
                    SendReceiveAP(Slew_Cmd, "Button Rate", False, 0)
                End If
                If CheckBoxFlipEW.Checked = False Then
                    Cmd = ":Mw#"
                    Msg = "Slewing West"
                Else
                    Cmd = ":Me#"
                    Msg = "Slewing East"
                End If
                ButtonW.BackColor = ActiveColor
            Case "Stop"
                Cmd = ":Q#"
                ButtonN.BackColor = NormColor
                ButtonS.BackColor = NormColor
                ButtonE.BackColor = NormColor
                ButtonW.BackColor = NormColor
                Msg = "Slewing Stop"
            Case "StopN"
                If CheckBoxFlipNS.Checked = False Then
                    Cmd = ":Qn#"
                    Msg = "Slewing North Stop"
                Else
                    Cmd = ":Qs#"
                    Msg = "Slewing South Stop"
                End If
                ButtonN.BackColor = NormColor
            Case "StopS"
                If CheckBoxFlipNS.Checked = False Then
                    Cmd = ":Qs#"
                    Msg = "Slewing South Stop"
                Else
                    Cmd = ":Qn#"
                    Msg = "Slewing North Stop"
                End If
                ButtonS.BackColor = NormColor
            Case "StopE"
                If CheckBoxFlipEW.Checked = False Then
                    Cmd = ":Qe#"
                    Msg = "Slewing East Stop"
                Else
                    Cmd = ":Qw#"
                    Msg = "Slewing West Stop"
                End If
                ButtonE.BackColor = NormColor
            Case "StopW"
                If CheckBoxFlipEW.Checked = False Then
                    Cmd = ":Qw#"
                    Msg = "Slewing West Stop"
                Else
                    Cmd = ":Qe#"
                    Msg = "Slewing East Stop"
                End If
                ButtonW.BackColor = NormColor

            Case "FocusIn"
                Cmd = ":F-#"
                Form_FOCUS.ButtonFocusIn.BackColor = ActiveColor
                Msg = "Focusing In"
            Case "FocusOut"
                Cmd = ":F+#"
                Form_FOCUS.ButtonFocusOut.BackColor = ActiveColor
                Msg = "Focusing Out"
            Case "FocusStop"
                Cmd = ":FQ#"
                Form_FOCUS.ButtonFocusIn.BackColor = NormColor
                Form_FOCUS.ButtonFocusOut.BackColor = NormColor
                Msg = "Focusing Stop"
            Case "FocusFast"
                Cmd = ":FF#"
                Msg = "Focus Fast"
            Case "FocusSlow"
                Cmd = ":FS#"
                Msg = "Focus Slow"

            Case "TrackingSideral"
                Cmd = ":RT2#"
                Msg = "Sidereal tracking rate"
                RadioButtonSideral.Checked = True
            Case "TrackingSolar"
                Cmd = ":RT1#"
                Msg = "Solar tracking rate"
                RadioButtonSolar.Checked = True
            Case "TrackingLunar"
                Cmd = ":RT0#"
                Msg = "Lunar tracking rate"
                RadioButtonLunar.Checked = True
            Case "TrackingStop"
                Cmd = ":RT9#"
                Msg = "Stop tracking rate"
                RadioButtonStop.Checked = True

            Case "SiderealTime"
                SendCmd = False
                Status = ""
                Cmd = ":GS#"
                SendReceiveAP(Cmd, "Sidereal Time", True, 0)
                TelescopeST = ""
                If Microsoft.VisualBasic.Right(Rsp, 1) = "#" Then
                    TelescopeST = Microsoft.VisualBasic.Left(Rsp, Len(Rsp) - 1)
                    Status = "Telescope sidereal time: " & TelescopeST
                Else
                    If Rsp = "" Then
                        Status = "Invalid or No response"
                        LineColor = Color.DarkRed
                    End If
                End If
                If MonitorCmd = False Then
                    StatusLabel.Text = Status
                End If

            Case "Latitude"
                SendCmd = False
                Status = ""
                Cmd = ":Gt#"
                SendReceiveAP(":Gt#", "Latitude", True, 0)
                TelescopeLat = ""
                If Microsoft.VisualBasic.Right(Rsp, 1) = "#" Then
                    TelescopeLat = Microsoft.VisualBasic.Left(Rsp, Len(Rsp) - 1)
                    Status = "Telescope latitude: " & TelescopeLat
                Else
                    If Rsp = "" Then
                        Status = "Invalid or No response"
                        LineColor = Color.DarkRed
                    End If
                End If
                If MonitorCmd = False Then
                    StatusLabel.Text = Status
                End If

            Case "GetMeridianOffset"
                SendCmd = False
                Status = ""
                Cmd = ":GM#"
                If AscomConnect = True Then
                    StatusLabel.Text = "Not supported via ASCOM"
                Else
                    SendReceiveAP(Cmd, "Get Meridian Offset", True, 0)
                    Resp = Rsp
                    MeridianOffset = ""
                    If Microsoft.VisualBasic.Right(Resp, 1) = "#" Then
                        MeridianOffset = Resp
                        Status = "Telescope Meridian Offset " & Microsoft.VisualBasic.Left(Resp, Len(Resp) - 1)
                    Else
                        If Resp = "" Then
                            Status = "No response"
                            LineColor = Color.DarkRed
                        End If
                    End If
                    If MonitorCmd = False Then
                        StatusLabel.Text = Status
                    End If
                End If

            Case "GetVersion"
                SendCmd = False
                Status = ""
                Cmd = ":V#"
                If AscomConnect = True Then
                    Resp = "V2#"
                Else
                    SendReceiveAP(Cmd, "Version", True, 0)
                    Resp = Rsp
                End If
                LabelSlewRateVar.Enabled = False
                LabelCenterRateVar.Enabled = False
                Form_SEARCH.ButtonVar.Enabled = False
                NumericUpDownRate.Enabled = False
                NumericUpDownRateC.Enabled = False

                If Resp.Length > 1 Then
                    Dim V As String
                    V = Microsoft.VisualBasic.Left(Resp, Len(Resp) - 1)
                    Dim V1 = Microsoft.VisualBasic.Left(Resp, 1)
                    LabelCenterRateVar.Text = "CP3"
                    LabelSlewRateVar.Text = "Goto CP3"
                    Select Case V1
                        Case "B", "C", "D", "E", "E", "K"
                            CP3 = False
                            CP3GOS = False
                            CP4 = False
                            Status = "Servo controller version " & V & " CP2"

                        Case "F", "G", "H", "I", "J", "L", "M", "N", "O", "P", "Q", "R", "S", "V"
                            LabelSlewRateVar.Enabled = True
                            LabelCenterRateVar.Enabled = True
                            Form_SEARCH.ButtonVar.Enabled = True
                            NumericUpDownRate.Enabled = True
                            NumericUpDownRateC.Enabled = True
                            CP3 = True
                            CP3GOS = False
                            Status = "Servo controller version " & V & " CP3"
                            If V1 = "V" Then
                                CP3GOS = True
                                CP4 = False
                            End If
                            If Mid(Resp, 1, 4) = "VCP4" Then
                                CP3 = True
                                CP4 = True
                                Status = "Servo controller version " & V & " CP4"
                                LabelCenterRateVar.Text = "CP4"
                                LabelSlewRateVar.Text = "Goto CP4"
                            End If
                        Case Else
                            CP3 = False
                            CP4 = False
                            CP3GOS = False
                            Status = "Unknown verison returned " & V
                    End Select

                Else
                    If Resp = "" Then
                        Status = "No response, or version less than B"
                    End If
                End If
                ServoVersion = Status
                UpdateStatusLine(Status, LineColor)

            Case "Init"
                If AscomConnect = True Then
                    SendCmd = False
                Else
                    Cmd = "#"
                    Msg = "Initialize mount"
                End If

            Case "SetFormat"
                If AscomConnect = True Then
                    SendCmd = False
                Else
                    Cmd = ":U#"
                    Msg = "Set long format " & Cmd
                End If

            Case "MountOperatingStatus"
                SendCmd = False
                Status = ""
                Cmd = ":GOS#"
                If AscomConnect = True Then
                    Resp = "Not supported"
                Else
                    SendTheCommand()
                    ' 029000220O000#                CP3
                    ' 099000261O000039#             CP4
                    Dim GOSlen As Integer = 14
                    If CP4 = True Then
                        GOSlen = 17
                    End If
                    If APnetwork = False Then
                        ' get response from ap mount via com port
                        tickBegin = Int(Date.Now.Ticks / 10000000)
                        Do Until Resp.Length >= GOSlen
                            Resp = Resp & SerialPort1.ReadExisting()
                            tickEnd = Int(Date.Now.Ticks / 10000000)
                            If tickEnd - tickBegin > ReadTimeout Then
                                MountReadError()
                                Exit Do
                            End If
                        Loop
                    Else
                        ' get response from ap mount via network connection
                        Try
                            Resp = GetTheResponse()
                        Catch ex As Exception
                            LogScope("TCP < ", Color.DarkRed, ex.Message)
                            MountReadError()
                        End Try
                    End If
                End If
                Rsp = Resp
                GOSresp = Resp

                If Microsoft.VisualBasic.Right(Resp, 1) = "#" Then
                    Resp_GOS.A = Mid(Resp, 1, 1)
                    Resp_GOS.B = Mid(Resp, 2, 1)
                    Resp_GOS.C = Mid(Resp, 3, 1)
                    Resp_GOS.D = Mid(Resp, 4, 1)
                    Resp_GOS.E = Mid(Resp, 5, 1)
                    Resp_GOS.F = Mid(Resp, 6, 1)
                    Resp_GOS.G = Mid(Resp, 7, 1)
                    Resp_GOS.H = Mid(Resp, 8, 1)
                    Resp_GOS.I = Mid(Resp, 9, 1)
                    Resp_GOS.J = Mid(Resp, 10, 1)
                    Resp_GOS.K = Mid(Resp, 11, 1)
                    Resp_GOS.L = Mid(Resp, 12, 1)
                    Resp_GOS.M = Mid(Resp, 13, 1)
                    Resp_GOS.N = Mid(Resp, 14, 1)

                    ' RA Tracking Status
                    Select Case Resp_GOS.B
                        Case "0"
                            ' Lunar Rate
                            RadioButtonLunar.Checked = True

                        Case "1"
                            ' Solar Rate
                            RadioButtonSolar.Checked = True

                        Case "2"
                            ' Sidereal
                            RadioButtonSideral.Checked = True

                        Case "9"
                            ' Tracking Stopped
                            RadioButtonStop.Checked = True

                    End Select

                End If
                LogResponse()
                UpdateStatusLine(ServoVersion & " GOS", LineColor)



        End Select

        If SendCmd = True Then
            SendTheCommand()
        End If

    End Sub

    Public Sub MountReadError()
        UpdateStatusLine("AP mount read error, timeout " & ReadTimeout & " secs.", Color.DarkRed)

    End Sub

    Public Sub SendTheCommand()
        Dim ApRec(50) As Byte

        UpdateStatusLine(Msg, Color.Black)
        If AscomConnect = True Then
            If CurrentRate <> "" Then
                SendReceiveAP(CurrentRate, Command, AscomRespSent, 0)
            End If
            SendReceiveAP(Cmd, Command, AscomRespSent, 0)
        Else
            If APnetwork = False Then
                SerialPort1.Write(Cmd)
            Else
                Try
                    ApRec = Encoding.ASCII.GetBytes(Cmd)
                    networkStream.Write(ApRec, 0, Cmd.Length)
                Catch ex As Exception
                    LogScope("TCP > ", Color.DarkRed, ex.Message)
                    Dim Line As String = "AP mount network write - ERROR, see log"
                    UpdateStatusLine(Line, Color.DarkRed)
                    Exit Sub
                End Try
            End If
            LogScope("Sent > ", Color.DarkBlue, Cmd)
        End If
        Msg = ""

    End Sub

    Function GetTheResponse()
        Dim TermChr As String = "#"
        If CP4ip = True Then
            TermChr = Chr(10)
        End If
        Do
            NumBytesRead = networkStream.Read(MountRec, 0, MountRec.Length)
            Resp = Resp & Encoding.ASCII.GetString(MountRec, 0, NumBytesRead)
        Loop Until Microsoft.VisualBasic.Right(Resp, "1") = TermChr
        If CP4ip = True Then
            Resp = Mid(Resp, 1, Resp.Length - 1)
        End If
        If Form_ControlP.CheckBoxDebugLogging.Checked = True Then
            LogScope("Debug TCP < (", Color.SaddleBrown, Resp.Length & ") " & Resp)
        End If
        ' remove any mount power up data
        Dim Resp2 As String = Resp
        Do While Mid(Resp2, 1, 2) = "Y1"
            Resp2 = Resp2.Replace("Y1", "")
        Loop
        GetTheResponse = Resp2

    End Function

    Private Sub LogResponse()
        LogScope("Resp < ", Color.DarkGreen, Resp)

    End Sub

    Public Sub UpdateStatusLine(ByVal Line As String, ByVal Color As Color)
        StatusLabel.Text = Line
        If Line <> "" Then
            LogScope("Status = ", Color, Line)
        End If

    End Sub

    Private Sub RadioButtonSideral_Click(sender As Object, e As System.EventArgs) Handles RadioButtonSideral.Click
        If SerialPort1.IsOpen = True Or SocketIsOpen = True Or IsConnected = True Then
            If RadioButtonSideral.Checked = True Then
                AP_Command("TrackingSideral")
            End If
        Else
            RadioButtonSideral.Checked = False
        End If

    End Sub

    Private Sub RadioButtonLunar_Click(sender As Object, e As System.EventArgs) Handles RadioButtonLunar.Click
        If RadioButtonLunar.Checked = True Then
            AP_Command("TrackingLunar")
        End If

    End Sub

    Private Sub RadioButtonSolar_Click(sender As Object, e As System.EventArgs) Handles RadioButtonSolar.Click
        If RadioButtonSolar.Checked = True Then
            AP_Command("TrackingSolar")
        End If

    End Sub

    Private Sub RadioButtonStop_Click(sender As Object, e As System.EventArgs) Handles RadioButtonStop.Click
        If RadioButtonStop.Checked = True Then
            AP_Command("TrackingStop")
        End If

    End Sub

    Private Sub ZeroCounterNS()
        NorthSouthCount = 0
        TextBoxNScount.Text = NorthSouthCount

    End Sub

    Private Sub ZeroCounterEW()
        EastWestCount = 0
        TextBoxEWcount.Text = EastWestCount

    End Sub

    Private Sub LabelClearSlew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LabelClearSlew.Click
        ZeroCounterNS()
        ZeroCounterEW()

    End Sub

    Private Sub LabelClearSlew_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles LabelClearSlew.MouseEnter
        SaveHoverColor = LabelClearSlew.BackColor
        LabelClearSlew.BackColor = ActiveColor

    End Sub

    Private Sub LabelClearSlew_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles LabelClearSlew.MouseLeave
        LabelClearSlew.BackColor = SaveHoverColor

    End Sub

    Private Sub SlewSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SlewSave.Click
        Dim RA_DEC_vis As Boolean

        If SerialPort1.IsOpen = True Or SocketIsOpen = True Or IsConnected = True Then
            RA_DEC_vis = Form_RA_DEC.Visible
            Form_RA_DEC.Show()
            Form_RA_DEC.ButtonGetRD.PerformClick()
            Application.DoEvents()
            Thread.Sleep(1000)
            Form_RA_DEC.Visible = RA_DEC_vis
            If RAtext = "" Then
                UpdateStatusLine("Save RA/DEC error", Color.DarkRed)
            Else
                UpdateStatusLine("Saved   " & RAtext & "  " & DECtext, Color.Black)
                SlewRestore.Enabled = True
                LabelShowRestore.Enabled = True
                'SlewRestore.BackColor = ButtonFocusRestore.BackColor
                SavedRA(1) = Format(Form_RA_DEC.RAh.Value, "00")
                SavedRA(2) = Format(Form_RA_DEC.RAm.Value, "00")
                SavedRA(3) = Format(Form_RA_DEC.RAs.Value, "00")
                SavedRA(4) = Form_RA_DEC.RAss.Value
                SavedDEC(1) = Form_RA_DEC.DECplus.Checked
                SavedDEC(2) = Form_RA_DEC.DECminus.Checked
                SavedDEC(3) = Format(Form_RA_DEC.DECd.Value, "00")
                SavedDEC(4) = Format(Form_RA_DEC.DECm.Value, "00")
                SavedDEC(5) = Format(Form_RA_DEC.DECs.Value, "00")
                SavedRaFull = AP_RA
                SavedDecFull = AP_DEC
                'SlewSave.BackColor = EnableColor
                'SlewRestore.BackColor = EnableColor
            End If
        End If

    End Sub

    Private Sub SlewRestore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SlewRestore.Click
        Dim RA_DEC_vis As Boolean

        If SerialPort1.IsOpen = True Or SocketIsOpen = True Or IsConnected = True Then
            RA_DEC_vis = Form_RA_DEC.Visible
            Form_RA_DEC.Show()
            Form_RA_DEC.RAh.Value = SavedRA(1)
            Form_RA_DEC.RAm.Value = SavedRA(2)
            Form_RA_DEC.RAs.Value = SavedRA(3)
            Form_RA_DEC.RAss.Value = SavedRA(4)
            Form_RA_DEC.DECplus.Checked = SavedDEC(1)
            Form_RA_DEC.DECminus.Checked = SavedDEC(2)
            Form_RA_DEC.DECd.Value = SavedDEC(3)
            Form_RA_DEC.DECm.Value = SavedDEC(4)
            Form_RA_DEC.DECs.Value = SavedDEC(5)
            Form_RA_DEC.ButtonGotoRD.PerformClick()
            Application.DoEvents()
            Thread.Sleep(1000)
            Form_RA_DEC.Visible = RA_DEC_vis
            If RAtext = "" Then
                UpdateStatusLine("Restore RA/DEC error", Color.Black)
            Else
                UpdateStatusLine("Restored   " & RAtext & "  " & DECtext, Color.Black)
                ZeroCounterNS()
                ZeroCounterEW()
            End If
        End If

    End Sub

    Private Sub LabelShowRestore_Click(sender As System.Object, e As System.EventArgs) Handles LabelShowRestore.Click
        Dim RestoreRa As String = ""
        Dim RestoreDec As String = ""
        RestoreRa = SavedRA(1) & "h " & SavedRA(2) & "m " & SavedRA(3) & "." & SavedRA(4) & "s"
        If SavedDEC(1) = "1" Then
            RestoreDec = "+"
        Else
            RestoreDec = "-"
        End If
        RestoreDec = RestoreDec & SavedDEC(3) & "° " & SavedDEC(4) & "' " & SavedDEC(5) & """"
        UpdateStatusLine("Restore set to  " & RestoreRa & "  " & RestoreDec, Color.Black)

    End Sub

    Private Sub Form1_LocationChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LocationChanged
        If Me.WindowState = FormWindowState.Minimized Then
            FormRestore(1) = Form_DATE_TIME.Visible
            FormRestore(2) = Form_RA_DEC.Visible
            FormRestore(3) = Form_SEARCH.Visible
            FormRestore(4) = Form_SYNC.Visible
            FormRestore(5) = Form_AZ_EL.Visible
            Form_DATE_TIME.Visible = False
            Form_RA_DEC.Visible = False
            Form_SEARCH.Visible = False
            Form_SYNC.Visible = False
            Form_AZ_EL.Visible = False
            NeedToRestore = True
        End If
        If Me.WindowState = FormWindowState.Normal Then
            If NeedToRestore = True Then
                Form_DATE_TIME.Visible = FormRestore(1)
                Form_RA_DEC.Visible = FormRestore(2)
                Form_SEARCH.Visible = FormRestore(3)
                Form_SYNC.Visible = FormRestore(4)
                Form_AZ_EL.Visible = FormRestore(5)
                NeedToRestore = False
            End If
        End If

    End Sub

    Private Sub AboutToolStripMenuItem_Click_1(sender As System.Object, e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        Form_ControlP.Show()
        Form_ControlP.TabControlP.SelectedIndex = 5
        Form_ControlP.Focus()

    End Sub

    Private Sub RADECToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Form_RA_DEC.Show()
        Form_RA_DEC.Focus()

    End Sub

    Private Sub SyncToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SyncToolStripMenuItem.Click
        Form_SYNC.Show()
        Form_SYNC.Focus()

    End Sub

    Private Sub TimerN_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerN.Tick
        TimerN.Enabled = False
        TimerProgN.Enabled = False
        AP_Command("StopN")
        NorthSouthCount = NSrealCount
        UpdateNScount()
        If Ding = True Then
            My.Computer.Audio.Play(My.Resources.ding, AudioPlayMode.WaitToComplete)
        End If

    End Sub

    Private Sub TimerS_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerS.Tick
        TimerS.Enabled = False
        TimerProgS.Enabled = False
        AP_Command("StopS")
        NorthSouthCount = NSrealCount
        UpdateNScount()
        If Ding = True Then
            My.Computer.Audio.Play(My.Resources.ding, AudioPlayMode.WaitToComplete)
        End If

    End Sub

    Private Sub TimerE_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerE.Tick
        TimerE.Enabled = False
        TimerProgE.Enabled = False
        AP_Command("StopE")
        EastWestCount = EWrealCount
        UpdateEWcount()
        If Ding = True Then
            My.Computer.Audio.Play(My.Resources.ding, AudioPlayMode.WaitToComplete)
        End If

    End Sub

    Private Sub TimerW_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerW.Tick
        TimerW.Enabled = False
        TimerProgW.Enabled = False
        AP_Command("StopW")
        EastWestCount = EWrealCount
        UpdateEWcount()
        If Ding = True Then
            My.Computer.Audio.Play(My.Resources.ding, AudioPlayMode.WaitToComplete)
        End If

    End Sub

    Private Sub TimerProgN_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerProgN.Tick
        If ProgN <= 0 Then
            TimerProgN.Enabled = False
            If CheckBoxFlipNS.Checked = False Then
                NorthSouthCount = NorthSouthCount - SlewTime
            Else
                NorthSouthCount = NorthSouthCount + SlewTime
            End If
        End If
        If CheckBoxFlipNS.Checked = False Then
            NorthSouthCount = NorthSouthCount + TimerProgN.Interval
        Else
            NorthSouthCount = NorthSouthCount - TimerProgN.Interval
        End If
        UpdateNScount()
        ProgN = ProgN - 1

    End Sub

    Private Sub TimerProgS_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerProgS.Tick
        If ProgS <= 0 Then
            TimerProgS.Enabled = False
            If CheckBoxFlipNS.Checked = False Then
                NorthSouthCount = NorthSouthCount + SlewTime
            Else
                NorthSouthCount = NorthSouthCount - SlewTime
            End If
        End If
        If CheckBoxFlipNS.Checked = False Then
            NorthSouthCount = NorthSouthCount - TimerProgN.Interval
        Else
            NorthSouthCount = NorthSouthCount + TimerProgN.Interval
        End If
        UpdateNScount()
        ProgS = ProgS - 1

    End Sub

    Private Sub TimerProgE_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerProgE.Tick
        If ProgE <= 0 Then
            TimerProgE.Enabled = False
            If CheckBoxFlipEW.Checked = False Then
                EastWestCount = EastWestCount - SlewTime
            Else
                EastWestCount = EastWestCount + SlewTime
            End If
        End If
        If CheckBoxFlipEW.Checked = False Then
            EastWestCount = EastWestCount + TimerProgW.Interval
        Else
            EastWestCount = EastWestCount - TimerProgW.Interval
        End If
        UpdateEWcount()
        ProgE = ProgE - 1

    End Sub

    Private Sub TimerProgW_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerProgW.Tick
        If ProgW <= 0 Then
            TimerProgW.Enabled = False
            If CheckBoxFlipEW.Checked = False Then
                EastWestCount = EastWestCount + SlewTime
            Else
                EastWestCount = EastWestCount - SlewTime
            End If
        End If
        If CheckBoxFlipEW.Checked = False Then
            EastWestCount = EastWestCount - TimerProgW.Interval
        Else
            EastWestCount = EastWestCount + TimerProgW.Interval
        End If
        UpdateEWcount()
        ProgW = ProgW - 1

    End Sub

    Private Sub LabelSlewRate25_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles LabelSlewRate25.MouseEnter
        SHC1 = LabelSlewRate25.BackColor
        LabelSlewRate25.BackColor = ActiveColor

    End Sub

    Private Sub LabelSlewRate25_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles LabelSlewRate25.MouseLeave
        LabelSlewRate25.BackColor = SHC1

    End Sub

    Private Sub LabelSlewRate10_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles LabelSlewRate10.MouseEnter
        SHC3 = LabelSlewRate10.BackColor
        LabelSlewRate10.BackColor = ActiveColor

    End Sub

    Private Sub LabelSlewRate10_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles LabelSlewRate10.MouseLeave
        LabelSlewRate10.BackColor = SHC3

    End Sub

    Private Sub LabelSlewRate12_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles LabelSlewRate12.MouseEnter
        SHC4 = LabelSlewRate12.BackColor
        LabelSlewRate12.BackColor = ActiveColor

    End Sub

    Private Sub LabelSlewRate12_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles LabelSlewRate12.MouseLeave
        LabelSlewRate12.BackColor = SHC4

    End Sub

    Private Sub LabelSlewRate50_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles LabelSlewRate50.MouseEnter
        SHC2 = LabelSlewRate50.BackColor
        LabelSlewRate50.BackColor = ActiveColor

    End Sub

    Private Sub LabelSlewRate50_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles LabelSlewRate50.MouseLeave
        LabelSlewRate50.BackColor = SHC2

    End Sub

    Private Sub LabelSlewRate600_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles LabelSlewRate600.MouseEnter
        SHC6 = LabelSlewRate600.BackColor
        LabelSlewRate600.BackColor = ActiveColor

    End Sub

    Private Sub LabelSlewRate600_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles LabelSlewRate600.MouseLeave
        LabelSlewRate600.BackColor = SHC6

    End Sub

    Private Sub LabelSlewRate64_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles LabelSlewRate64.MouseEnter
        SHC5 = LabelSlewRate64.BackColor
        LabelSlewRate64.BackColor = ActiveColor

    End Sub

    Private Sub LabelSlewRate64_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles LabelSlewRate64.MouseLeave
        LabelSlewRate64.BackColor = SHC5

    End Sub

    Private Sub LabelCenterRateVar_MouseEnter(ByVal sender As Object, ByVal e As System.EventArgs) Handles LabelCenterRateVar.MouseEnter
        SHC7 = LabelCenterRateVar.BackColor
        LabelCenterRateVar.BackColor = ActiveColor

    End Sub

    Private Sub LabelCenterRateVar_MouseLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles LabelCenterRateVar.MouseLeave
        LabelCenterRateVar.BackColor = SHC7

    End Sub

    Private Sub ButtonSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSearch.Click
        Form_SEARCH.Show()
        Form_SEARCH.Focus()

    End Sub

    Private Sub AltitudeAzimuthToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Form_AZ_EL.Show()
        Form_AZ_EL.Focus()

    End Sub

    Private Sub DomeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DomeToolStripMenuItem.Click
        Form_Dome.Show()
        If Form_Dome.WindowState = FormWindowState.Minimized Then
            Form_Dome.WindowState = FormWindowState.Normal
        End If
        Form_Dome.Focus()

    End Sub

    ' Com combo box events
    Private Sub ToolStripComboBoxCom_MouseHover(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripComboBoxCom.MouseHover
        On Error Resume Next
        ToolStripComboBoxCom.ToolTipText = ToolStripComboBoxCom.Items(ToolStripComboBoxCom.SelectedIndex)

    End Sub

    Private Sub ToolStripComboBoxCom_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ToolStripComboBoxCom.SelectedIndexChanged
        ToolStripComboBoxCom.ToolTipText = ToolStripComboBoxCom.Items(ToolStripComboBoxCom.SelectedIndex)
        If ToolStripComboBoxCom.Items(ToolStripComboBoxCom.SelectedIndex) = "ASCOM" Then
            ButtonConnect.Width = 89
            ButtonChoose.Visible = True
        Else
            ButtonConnect.Width = ButtonConnect2.Width
            ButtonChoose.Visible = False
        End If

    End Sub

    ' Com2 combo box events
    Private Sub ComboBoxCom2_MouseHover(sender As Object, e As System.EventArgs) Handles ComboBoxCom2.MouseHover
        ToolTip1.SetToolTip(ComboBoxCom2, ComboBoxCom2.Items(ComboBoxCom2.SelectedIndex))

    End Sub

    Private Sub ComboBoxCom2_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles ComboBoxCom2.SelectedIndexChanged
        ToolTip1.SetToolTip(ComboBoxCom2, ComboBoxCom2.Items(ComboBoxCom2.SelectedIndex))

    End Sub
    ' display full status text in popup window
    Private Sub StatusLabel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles StatusLabel.Click
        Dim S As String

        S = StatusLabel.Text
        If S.Length > 0 Then
            Form_MSG_TEXT.TextBoxMsg.Text = S
            Form_MSG_TEXT.TextBoxMsg.Select(Form_MSG_TEXT.TextBoxMsg.Text.Length, 0)
            Form_MSG_TEXT.Show()
        End If

    End Sub

    Private Sub StatusLabel_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles StatusLabel.MouseUp
        If (e.Button = Windows.Forms.MouseButtons.Right) Then
            StatusLabel.Text = ""
        End If

    End Sub

    Private Sub StatusLabel_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles StatusLabel.TextChanged
        StatusLabel.ToolTipText = StatusLabel.Text

    End Sub

    Private Sub ToolStripMenuItem4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem4.Click
        Form_SENT_RESP_LOG.Show()
        Form_SENT_RESP_LOG.Focus()

    End Sub

    Public Sub ScopePositionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ScopePositionToolStripMenuItem.Click
        Dim TelescopeMoving As String = " "
        Dim TelescopeNS As String = " "
        Dim TelescopeEW As String = " "

        If SerialPort1.IsOpen = True Or SocketIsOpen = True Or IsConnected = True Then
            Try
                MonitorCmd = True
                GetScopeRaDec()
                GetScopeAzEl()
                GetMeridianDist()

                Form_Monitor.AP_RA = AP_RA
                Form_Monitor.AP_DEC = AP_DEC

                TelescopeLastRA = TelescopeCurRA
                TelescopeCurRA = (Mid(AP_RA, 1, 2) * 3600) + (Mid(AP_RA, 4, 2) * 60) + (Mid(AP_RA, 7, 4))
                If TelescopeLastRA <> 0 Then
                    If TelescopeCurRA < TelescopeLastRA Then
                        TelescopeEW = "West"
                    End If
                    If TelescopeCurRA > TelescopeLastRA Then
                        TelescopeEW = "East"
                    End If
                End If

                TelescopeLastDEC = TelescopeCurDEC
                TelescopeCurDEC = (Mid(AP_DEC, 2, 2) * 60) + (Mid(AP_DEC, 5, 2) * 60) + (Mid(AP_DEC, 8, 2))
                If Mid(AP_DEC, 1, 1) = "-" Then
                    TelescopeCurDEC = TelescopeCurDEC * -1
                End If
                If TelescopeLastDEC <> 0 Then
                    If TelescopeCurDEC < TelescopeLastDEC Then
                        TelescopeNS = "South"
                    End If
                    If TelescopeCurDEC > TelescopeLastDEC Then
                        TelescopeNS = "North"
                    End If
                End If

                If TelescopeNS <> " " And TelescopeEW <> " " Then
                    TelescopeMoving = TelescopeNS & "-" & TelescopeEW
                Else
                    If TelescopeNS <> " " Then
                        TelescopeMoving = TelescopeNS
                    Else
                        TelescopeMoving = TelescopeEW
                    End If
                End If

                Update_Scope_Pos()

                If TelescopeMoving <> " " Then
                    With Form_Monitor.TextPos
                        .SelectionColor = Lcolor2
                        .SelectedText = "Moved: "
                        .SelectionColor = Dcolor2
                        .SelectedText = TelescopeMoving
                    End With
                End If

            Catch ex As Exception
                UpdateStatusLine(ex.Message, Color.DarkRed)

            End Try

            MonitorCmd = False
        Else
            With Form_Monitor.TextPos
                .Text = ""
                .SelectionColor = Color.OrangeRed
                .SelectedText = "Not connected"
            End With
        End If

        Form_Monitor.Visible = True
        Dim DT As String = Now
        Form_Monitor.Text = "Scope & Dome Position  " & DT
        If TelescopeST <> "" Then
            Form_Monitor.Text = Form_Monitor.Text & "    " & TelescopeST & " ST"
        End If

    End Sub

    Public Sub Update_Scope_Pos()
        With Form_Monitor.TextPos
            .Text = ""
            .SelectionColor = Lcolor
            .SelectedText = "Ra: "
            .SelectionColor = Dcolor
            .SelectedText = Mid(AP_RA, 1, 2) & "h " & Mid(AP_RA, 4, 2) & "m " & Mid(AP_RA, 7, 4) & "s  "

            .SelectionColor = Lcolor
            .SelectedText = "Dec: "
            .SelectionColor = Dcolor
            .SelectedText = Mid(AP_DEC, 1, 3) & "° " & Mid(AP_DEC, 5, 2) & "' " & Mid(AP_DEC, 8, 2) & """  "

            .SelectionColor = Lcolor
            .SelectedText = "Alt: "
            .SelectionColor = Dcolor
            .SelectedText = Mid(AP_AL, 1, 3) & "°   "
            .SelectionColor = Lcolor
            .SelectedText = "Az: "
            .SelectionColor = Dcolor
            .SelectedText = Az_Value & "°  "

            .SelectionColor = Lcolor
            .SelectedText = "Scope: "
            .SelectionColor = Dcolor
            .SelectedText = TelescopeSide & "  "

            .SelectionColor = Dcolor
            .SelectedText = AP_MeridianDist & "  "

            If Form_ControlP.CheckBoxStopMeridian.Checked = True Then

                If TelescopeSide = "West" Then
                    If AP_MeridianDeg < 0 Then
                        Dim DegMins As Single = Math.Abs((AP_MeridianDeg * 4) - MinsToMerStop)
                        Dim H As Integer = Int(DegMins / 60)
                        Dim M As Integer = DegMins - (H * 60)
                        .SelectionColor = Lcolor
                        .SelectedText = "Mer.Stop: "
                        .SelectionColor = Dcolor
                        .SelectedText = Format(H, "00h:") & Format(M, "00m ")
                    End If
                End If

            End If

            If Form_Dome.CheckBoxTrack.Checked = True Then
                .SelectionColor = Lcolor
                .SelectedText = "Dome: "
                .SelectionColor = Dcolor
                .SelectedText = Form_Dome.LabelDomeAz.Text & "°  "
            End If

        End With


    End Sub

    Public Sub Load_Domes()
        Dim S As Integer

        Path = Application.StartupPath()

        If DomesFileCustom = "" Then
            DomeFilename = Path & DomeDefaultFilename
        Else
            DomeFilename = DomesFileCustom
        End If

        Try
            If File.Exists(DomeFilename) = False Then
                S = MsgBox("Domes file:" & vbCrLf & DomeFilename & vbCrLf & "Does not exist." & vbCrLf & "Try to load default Dome file?", _
                        MsgBoxStyle.YesNo, "Error in domes file")
                If S = vbNo Then
                    UpdateStatusLine("Dome file not loaded: " & DomeFilename, Color.DarkRed)
                    Exit Sub
                Else
                    DomeFilename = Path & DomeDefaultFilename
                    UpdateStatusLine("Dome file not found: " & DomeFilename, Color.DarkRed)
                    UpdateStatusLine("trying default...", Color.Black)
                End If
            End If

            Using sr As StreamReader = New System.IO.StreamReader(DomeFilename, System.Text.Encoding.Default)
                Form_Dome.ComboBoxDomes.Items.Clear()
                Do Until sr.EndOfStream = True
                    Dim rec As String = sr.ReadLine
                    If Mid(rec, 1, 1) <> "!" Then
                        Form_Dome.ComboBoxDomes.Items.Add(rec)
                    End If
                Loop
                Form_Dome.ComboBoxDomes.SelectedIndex = DomeCurrent
                Form_Dome.EditObservatoriesDomesFileToolStripMenuItem.ToolTipText = DomeFilename
                Form_Dome.ResetDomesFileToDefaultToolStripMenuItem.ToolTipText = Path & DomeDefaultFilename
                UpdateStatusLine("Dome file loaded: " & DomeFilename, Color.Black)
                UpdateStatusLine("Dome Calculation Position index = " & DomeCurrent, Color.Black)
                sr.Close()
            End Using

        Catch ex As Exception
            MsgBox("Domes file:" & vbCrLf & DomeFilename & vbCrLf & vbCrLf & ex.Message, _
                    MsgBoxStyle.OkOnly, "Error in domes file")
            UpdateStatusLine("Dome file open error: " & DomeFilename & vbCrLf & ex.Message, Color.DarkRed)
        End Try

    End Sub

    Private Sub ClearStatusLineToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ClearStatusLineToolStripMenuItem.Click
        StatusLabel.Text = ""

    End Sub

    Private Sub AutoDomeTrackStartup_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AutoDomeTrackStartup.Click
        If AutoDomeTrackStartup.Checked = True Then
            AutoDomeTrackStartup.Checked = False
        Else
            AutoDomeTrackStartup.Checked = True
        End If

    End Sub

    Private Sub TimerAutoDomeTrack_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerAutoDomeTrack.Tick
        TimerAutoDomeTrack.Enabled = False
        Form_ControlP.CheckBoxStopDur.Checked = My.Settings.StopDur
        Form_ControlP.CheckBoxStopMeridian.Checked = My.Settings.StopMer

        Form_Dome.AutoDomeTrackStarting = True
        AutoDomeTrack()
        Form_Dome.AutoDomeTrackStarting = False

        'KeyControl.Focus()

    End Sub

    Private Sub Position1ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Position1ToolStripMenuItem.Click
        Dim AP_AL As String = ""
        Dim AP_AZ As String = ""

        AP_AL = ":Sa +00*00:00#"
        AP_AZ = ":Sz 359*59:59#"
        ParkScope(1, AP_AL, AP_AZ)

    End Sub

    Private Sub Position2ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Position2ToolStripMenuItem.Click
        Dim AP_AL As String = ""
        Dim AP_AZ As String = ""

        AP_AL = ":Sa +00*00:00#"
        AP_AZ = ":Sz 090*00:00#"
        ParkScope(2, AP_AL, AP_AZ)

    End Sub

    Private Sub Position3ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Position3ToolStripMenuItem.Click
        Dim AP_AL As String = ""
        Dim AP_AZ As String = ""

        AP_Command("Latitude")
        AP_AL = ":Sa " & TelescopeLat & "#"
        AP_AZ = ":Sz 000*00:00#"
        ParkScope(3, AP_AL, AP_AZ)

    End Sub

    Private Sub Position4ToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles Position4ToolStripMenuItem.Click
        If AP_AL_Park4 = "" Then
            StatusLabel.Text = "Park position 4 has not been set"
        Else
            Dim AP_AL As String = ""
            Dim AP_AZ As String = ""

            AP_AL = AP_AL_Park4
            AP_AZ = AP_AZ_Park4
            ParkScope(4, AP_AL, AP_AZ)
        End If

    End Sub

    Private Sub ParkScope(ByVal Pos As Integer, ByVal AP_AL As String, ByVal AP_AZ As String)
        Dim tickBegin, tickEnd As Long
        Dim MountTrackingStop As String = " ,tracking stopped"
        Dim MT As String = ""

        If SerialPort1.IsOpen = True Or SocketIsOpen = True Or IsConnected = True Then
            Resp = ""

            'stop tracking if option is set
            If StopOnPark = True Then
                MT = MountTrackingStop
                RadioButtonStop.PerformClick()
            End If

            ' clear meridian offset if set
            If MeridianOffset <> "00:00:00.0#" Then
                Form_Meridian.ButtonClear.PerformClick()
            End If

            If AscomConnect = True Then
                SendReceiveAP(AP_AZ, "Azimuth", True, 1)
                SendReceiveAP(AP_AL, "Altitude", True, 1)
                SendReceiveAP(":MS#", "Slew", True, 1)
                If Rsp = "0" Then
                    If Form_Dome.CheckBoxTrack.Checked = True Then
                        Form_Dome.CheckBoxTrack.Checked = False
                    End If
                    UpdateStatusLine("Goto Park " & Pos & " successful" & MT, Color.Black)
                End If

            Else
                If APnetwork = False Then
                    ' serial port connection to AP mount
                    Try
                        SerialPort1.Write(AP_AZ & AP_AL)
                        LogScope("Sent > ", Color.DarkBlue, AP_AL & AP_AZ)
                        tickBegin = Int(Date.Now.Ticks / 10000000)
                        Do Until Resp.Length >= 2
                            Resp = Resp & SerialPort1.ReadExisting()
                            tickEnd = Int(Date.Now.Ticks / 10000000)
                            If tickEnd - tickBegin > ReadTimeout Then
                                UpdateStatusLine("Timeout sending Az/Al", Color.DarkRed)
                                Exit Do
                            End If
                        Loop
                        LogScope("Resp < ", Color.DarkGreen, Resp)
                        Rsp = Resp

                        If Resp = "11" Then
                            Resp = ""
                            SerialPort1.Write(":MS#")
                            LogScope("Sent > :MS#", Color.DarkBlue, "")
                            tickBegin = Int(Date.Now.Ticks / 10000000)
                            Do Until Resp.Length >= 1
                                Resp = Resp & SerialPort1.ReadExisting()
                                tickEnd = Int(Date.Now.Ticks / 10000000)
                                If tickEnd - tickBegin > ReadTimeout Then
                                    UpdateStatusLine("Timeout sending slew", Color.DarkRed)
                                    Exit Do
                                End If
                            Loop
                            LogScope("Resp < ", Color.DarkGreen, Resp)
                            Rsp = Resp
                            If Resp = "0" Then
                                If Form_Dome.CheckBoxTrack.Checked = True Then
                                    Form_Dome.CheckBoxTrack.Checked = False
                                End If
                                UpdateStatusLine("Goto Park " & Pos & " successful" & MT, Color.Black)
                            End If
                        End If
                    Catch ex As Exception
                        If ErrorMsgBox = True Then
                            Dim M As String
                            M = ex.Message & vbCrLf & "AZ = " & AP_AZ & vbCrLf & "AL = " & AP_AL
                            MsgBox(M, MsgBoxStyle.OkOnly, "Goto AZ/AL Error")
                        End If
                        UpdateStatusLine("Park Scope failed", Color.DarkRed)
                    End Try

                Else

                    ' network connection to AP mount
                    Try
                        Dim ApRec(50) As Byte
                        Dim Cmd As String = AP_AL & AP_AZ
                        ApRec = Encoding.ASCII.GetBytes(Cmd)
                        networkStream.Write(ApRec, 0, Cmd.Length)
                        LogScope("Sent > ", Color.DarkBlue, AP_AL & AP_AZ)

                        Dim TermChr As String = "11"
                        Dim TermChrLen As Integer = 2
                        Dim RespLen As Integer = 1
                        If CP4ip = True Then
                            TermChr = "1" & Chr(10) & "1" & Chr(10)
                            TermChrLen = 4
                            RespLen = 2
                        End If
                        Do
                            NumBytesRead = networkStream.Read(MountRec, 0, MountRec.Length)
                            Resp = Resp & Encoding.ASCII.GetString(MountRec, 0, NumBytesRead)
                        Loop Until Microsoft.VisualBasic.Right(Resp, TermChrLen) = TermChr

                        Resp = Resp.Replace(Chr(10), "")
                        LogScope("Resp > ", Color.DarkGreen, Resp)

                        If Resp = "11" Then
                            Resp = ""
                            Dim Cmd2 As String = ":MS#"
                            ApRec = Encoding.ASCII.GetBytes(Cmd2)
                            networkStream.Write(ApRec, 0, Cmd2.Length)
                            LogScope("Sent > ", Color.DarkBlue, Cmd2)

                            Do
                                NumBytesRead = networkStream.Read(MountRec, 0, MountRec.Length)
                                Resp = Resp & Encoding.ASCII.GetString(MountRec, 0, NumBytesRead)
                            Loop Until Resp.Length = RespLen
                            Resp = Resp.Replace(Chr(10), "")
                            Rsp = Resp
                            If Resp = "0" Then
                                If Form_Dome.CheckBoxTrack.Checked = True Then
                                    Form_Dome.CheckBoxTrack.Checked = False
                                End If
                                UpdateStatusLine("Goto Park " & Pos & " successful" & MT, Color.Black)
                            End If
                        End If
                    Catch ex As Exception
                        If ErrorMsgBox = True Then
                            Dim M As String
                            M = ex.Message & vbCrLf & "AZ = " & AP_AZ & vbCrLf & "AL = " & AP_AL
                            MsgBox(M, MsgBoxStyle.OkOnly, "Goto AZ/AL Error")
                        End If
                        UpdateStatusLine("Park Scope failed", Color.DarkRed)
                    End Try

                End If

            End If

        End If

    End Sub

    Public Sub LogScope(ByVal EntryType As String, ByVal EntryColor As Color, ByVal EntryLine As String)
        If Form_SENT_RESP_LOG.CheckBoxPause.Checked = False Then
            Dim D As TimeSpan = Now.TimeOfDay
            T = Format(D.Hours, "00") & ":" & Format(D.Minutes, "00") & ":" & Format(D.Seconds, "00") & _
                "." & Format(D.Milliseconds, "000") & "  "
            Form_SENT_RESP_LOG.RichTextBox1.SelectionColor = EntryColor
            Form_SENT_RESP_LOG.RichTextBox1.SelectedText = T & EntryType & EntryLine
            If EntryColor = Color.DarkRed Then
                Form_SENT_RESP_LOG.RichTextBox2.SelectionColor = EntryColor
                Form_SENT_RESP_LOG.RichTextBox2.SelectedText = T & EntryType & EntryLine
            End If
        End If

    End Sub

    Private Sub TimerMeridianStopDeg_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerMeridianStopDeg.Tick
        Dim StopDone As Boolean = False

        If SerialPort1.IsOpen = True Or SocketIsOpen = True Or IsConnected = True Then

            If Form_Dome.CheckBoxTrack.Checked = False Then
                GetScopeRaDec()
                GetScopeAzEl()
            End If

            GetMeridianDist()
            Dim MeridianStop As Integer = Form_ControlP.NumericUpDownStopDeg.Value

            If TelescopeSide = "West" Then
                If AP_MeridianDeg >= MeridianStop Then
                    RadioButtonStop.PerformClick()
                    StopDone = True
                    Form_ControlP.CheckBoxStopMeridian.Checked = False
                    Dim M As String = MeridianStop & "° past meridian, tracking stopped"
                    UpdateStatusLine(M, Color.Black)
                    Talker.SpeakAsync(M)
                End If
            End If

            If TelescopeSide = "East" Then
                If TelescopeLat = "" Then
                    AP_Command("Latitude")
                End If
                Dim Alt As Single = Mid(AP_AL, 1, 3)
                Dim Lat As Single = Mid(TelescopeLat, 1, 3)
                Dim Dec As Integer = Mid(AP_DEC, 1, 3)
                If Alt <= 5.0 Then
                    RadioButtonStop.PerformClick()
                    StopDone = True
                    Form_ControlP.CheckBoxStopMeridian.Checked = False
                    Dim M As String = "West altitude at 5°, tracking stopped"
                    UpdateStatusLine(M, Color.Black)
                    Talker.SpeakAsync(M)
                End If
            End If

            If StopDone = True Then
                M = "Tracking stopped by meridian timer"
                If MerTimerPark = True Then
                    ParkOnStop()
                End If
                CheckDisconnect()
                CheckStopPHD()
                CheckPwrOff()

                Form_Msg.TextBoxMsg.Text = M
                If MsgDoNotShow = False Then
                    Form_Msg.Show()
                End If
            End If

        End If

    End Sub

    Private Sub TimerMeridianStopDur_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TimerMeridianStopDur.Tick
        ' stop mount tracking
        RadioButtonStop.PerformClick()
        UpdateStatusLine("Tracking stopped by duration timer", Color.Black)

        Form_ControlP.CheckBoxStopDur.Checked = False

        If Form_Dome.DurTimerParksDome.Checked = True Then
            Form_Dome.ParkDome()
        End If

        M = "Tracking stopped by duration timer"
        Talker.SpeakAsync(M)
        If DurTimerPark = True Then
            ParkOnStop()
        End If
        CheckDisconnect()
        CheckStopPHD()
        CheckPwrOff()

        Form_Msg.TextBoxMsg.Text = M
        If MsgDoNotShow = False Then
            Form_Msg.Show()
        End If

    End Sub

    Private Sub TimerMeridianStopDurCnt_Tick(sender As System.Object, e As System.EventArgs) Handles TimerMeridianStopDurCnt.Tick
        ' update time remaining for meridian stop duration timer
        StopDurCnt = StopDurCnt - 1
        Form_ControlP.LabelCnt.Text = StopDurCnt
        LabelDurCnt.Text = StopDurCnt

    End Sub

    Private Sub TimerAltStopDeg_Tick(sender As System.Object, e As System.EventArgs) Handles TimerAltStopDeg.Tick
        If SerialPort1.IsOpen = True Or SocketIsOpen = True Or IsConnected = True Then
            Dim AltStop As Integer = Form_ControlP.NumericUpDownStopAlt.Value
            Dim CurAlt As Integer

            If Form_Dome.CheckBoxTrack.Checked = False Then
                GetScopeAzEl()
            End If

            CurAlt = Mid(AP_AL, 1, 3)

            If CurAlt <= AltStop Then
                RadioButtonStop.PerformClick()
                Form_ControlP.CheckBoxStopAlt.Checked = False
                Dim M As String = "Tracking stopped by altitude timer at " & AltStop & " degrees"
                UpdateStatusLine(M, Color.Black)
                Talker.SpeakAsync(M)
                If AltTimerPark = True Then
                    ParkOnStop()
                End If
                CheckDisconnect()
                CheckStopPHD()
                CheckPwrOff()

                Form_Msg.TextBoxMsg.Text = M
                If MsgDoNotShow = False Then
                    Form_Msg.Show()
                End If
            End If

        End If

    End Sub

    Private Sub ParkOnStop()
        If Form_ControlP.CheckBoxPark1.Checked = True Then
            Position1ToolStripMenuItem.PerformClick()
            M = M & ", park 1"
        End If
        If Form_ControlP.CheckBoxPark2.Checked = True Then
            Position2ToolStripMenuItem.PerformClick()
            M = M & ", park 2"
        End If
        If Form_ControlP.CheckBoxPark3.Checked = True Then
            Position3ToolStripMenuItem.PerformClick()
            M = M & ", park 3"
        End If
        If Form_ControlP.CheckBoxPark4.Checked = True Then
            Position4ToolStripMenuItem.PerformClick()
            M = M & ", park 4"
        End If

        UpdateStatusLine(M, Color.Black)
        Talker.Speak(M)

    End Sub

    Private Sub CheckDisconnect()
        ' Disconnect from mount and dome if option set
        If DurTimerDisconnect = True Then
            ' wait for mount to stop
            If SerialPort1.IsOpen = True Or SocketIsOpen = True Or IsConnected = True Then
                M = "Waiting for mount to stop movement"
                UpdateStatusLine(M, Color.Black)
                Talker.Speak(M)
                WaitMountStop()
                M = "Mount has stopped"
                UpdateStatusLine(M, Color.Black)
                Talker.Speak(M)
            End If

            ' disconnect from dome
            If Form_Dome.DomeConnected = True Then
                M = "Disconnecting from dome controller"
                UpdateStatusLine(M, Color.Black)
                Talker.Speak(M)
                Form_Dome.DisconnectDome()
            End If

            ' disconnect from mount
            If SerialPort1.IsOpen = True Or SocketIsOpen = True Or IsConnected = True Then
                M = "Disconnecting from telescope mount"
                UpdateStatusLine(M, Color.Black)
                Talker.Speak(M)
                ButtonConnect.PerformClick()
            End If
        End If

    End Sub

    Private Sub CheckPwrOff()
        ' power off relays if Xport power box is connected
        If DurTimerPwrOff = True Then
            Form_ControlP.PwrOff()
            M = "X port selected relays set to off"
            UpdateStatusLine(M, Color.Black)
            Talker.Speak(M)
            If DurTimerDisconnect = True Then
                If Form_ControlP.PwrBoxConnected = True Then
                    Form_ControlP.ButtonPower.PerformClick()
                End If
            End If
        End If

    End Sub

    Private Sub CheckStopPHD()
        If StopPHD = True Then
            Dim proc = Process.GetProcessesByName(Form_ControlP.TextBoxPHDname.Text)
            Try
                For Each p In proc
                    p.Kill()
                Next
                M = "Ending PHD process"
                UpdateStatusLine(M, Color.Black)
                Talker.Speak(M)
            Catch ex As Exception
                UpdateStatusLine("End PHD error: '" & ex.Message & "'", Color.DarkRed)
            End Try
        End If

    End Sub

    Private Sub WaitMountStop()
        Dim MountStopped As Boolean = False
        Dim AL1 As String = ""
        Dim AZ1 As String = ""
        Dim AL2 As String = ""
        Dim AZ2 As String = ""

        SendReceiveAP(":GA#", "ALT", True, 0)
        AL1 = Rsp
        SendReceiveAP(":GZ#", "AZ", True, 0)
        AZ1 = Rsp

        Form_ControlP.ButtonAbort.Visible = True
        Do While MountStopped = False And AbortStopWait = False
            Application.DoEvents()
            Thread.Sleep(2000)
            AL2 = AL1
            AZ2 = AZ1
            SendReceiveAP(":GA#", "ALT", True, 0)
            AL1 = Rsp
            SendReceiveAP(":GZ#", "AZ", True, 0)
            AZ1 = Rsp
            If AL1 = AL2 And AZ1 = AZ2 Then
                MountStopped = True
            End If
        Loop
        Form_ControlP.ButtonAbort.Visible = False
        AbortStopWait = False


    End Sub


    Public Sub AlwaysOnTop()
        Dim State As Boolean
        State = Form_ControlP.CheckBoxAlwaysOnTop.Checked
        Form_AZ_EL.TopMost = State
        Form_COM_PORTS.TopMost = State
        Form_DATE_TIME.TopMost = State
        Form_DIAGS.TopMost = State
        Form_Dome.TopMost = State
        Form_DOME_SENT_RESP_LOG.TopMost = State
        Form_DomeHelp.TopMost = State
        Form_FOCUS.TopMost = State
        Form_Monitor.TopMost = State
        Form_MSG_TEXT.TopMost = State
        Form_RA_DEC.TopMost = State
        Form_Save_Restore.TopMost = State
        Form_SEARCH.TopMost = State
        Form_SENT_RESP_LOG.TopMost = State
        Form_TrackingRate.TopMost = State
        Form_Web.TopMost = State
        Form_ControlP.TopMost = State
        Me.TopMost = State

    End Sub

    Private Sub SaveRestoreRADECToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveRestoreRADECToolStripMenuItem.Click
        Form_Save_Restore.Show()

    End Sub

    Private Sub GTOCP3TrackingRateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GTOCP3TrackingRateButton.Click
        Form_TrackingRate.Show()

    End Sub

    Private Sub TimerComNotFound_Tick(sender As System.Object, e As System.EventArgs) Handles TimerComNotFound.Tick
        TimerComNotFound.Enabled = False
        MsgBox(My.Settings.ComPort & " - does not exist, defaulting to 1st COM device.", MsgBoxStyle.OkOnly, "Saved COM port not found")

    End Sub


    Private Sub TimerSerial2BufferCheck_Tick(sender As System.Object, e As System.EventArgs) Handles TimerSerial2BufferCheck.Tick
        Dim DataRec() As String
        Dim U, B As Integer
        Dim PartCmd As String = ""
        Dim Resp_Req As Boolean
        Dim Resp_Length As Integer              ' 0 = read until # received

        InData2 = InData2 & SerialPort2.ReadExisting
        InBuf2Len = InData2.Length
        If InBuf2Len = 0 Then Exit Sub

        ' debug
        'LogScope("InData2 < ", Color.DarkViolet, InData2)

        ' SkyChart III LX200 connect
        If InData2 = Chr(6) Then
            LogScope("Rec2 < ", Color.DarkViolet, "<ACK>")
            SerialPort2.Write("A")
            LogScope("Sent2 > ", Color.DarkMagenta, "A")
            InData2 = Mid(InData2, 2, InData2.Length - 1)
        End If

        ' Split commands into array
        DataRec = Split(InData2, "#")
        U = UBound(DataRec)

        ' check for complete command at end of buffer
        If Microsoft.VisualBasic.Right(InData2, 1) <> "#" Then
            PartCmd = DataRec(U)
            U = U - 1
        End If

        ' Process commands
        If U > 0 Then
            For B = 0 To U

                ' Build command string
                AP_CMD2 = DataRec(B)
                If Microsoft.VisualBasic.Left(AP_CMD2, 1) = ":" Then
                    AP_CMD2 = AP_CMD2 & "#"
                End If

                DelayWrite = False
                IgnoreResp = False
                J2000Resp = False

                'Get Telescope command
                If Microsoft.VisualBasic.Right(AP_CMD2, 1) = "#" Then
                    ' Only send Focus commands to mount
                    If Microsoft.VisualBasic.Left(AP_CMD2, 1) = ":" Then
                        Dim Msg As String = "Com Port2 " & AP_CMD2
                        Dim Cmd3 As String = Mid(AP_CMD2, 1, 3)
                        Select Case Cmd3
                            Case ":GR"
                                If ToolStripMenuItemRDadjust.Checked = True Then
                                    J2000Resp = True
                                End If
                                Resp_Length = 0
                                Resp_Req = True

                            Case ":GD"
                                If ToolStripMenuItemRDadjust.Checked = True Then
                                    J2000Resp = True
                                End If
                                Resp_Length = 0
                                Resp_Req = True

                            Case ":GS", ":pS", ":GZ", ":GA", ":V#", _
                                 ":Gt", ":Gg", _
                                 ":SG", ":SL", ":SC", ":GG", ":GL", _
                                 ":GC", ":RR", ":CM", ":GM"
                                Resp_Length = 0
                                Resp_Req = True

                            Case ":Sa", ":Sz", ":St", ":Sg", ":MS", _
                                 ":Bd", ":Br", ":G", "SM" & Chr(5)
                                Resp_Length = 1
                                Resp_Req = True

                            Case ":Sr"
                                Resp_Length = 1
                                Resp_Req = True
                                If ToolStripMenuItemRDadjust.Checked = True Then
                                    If AP_CMD2.Length > 13 Then
                                        RaIn = Mid(AP_CMD2, 5, 10)
                                    Else
                                        RaIn = Mid(AP_CMD2, 5, 8) & ".0"
                                    End If
                                    AP_CMD2_RA = AP_CMD2
                                    DelayWrite = True
                                    IgnoreResp = True
                                    Rsp = "1"
                                End If

                            Case ":Sd"
                                Resp_Length = 1
                                Resp_Req = True
                                If ToolStripMenuItemRDadjust.Checked = True Then
                                    DecIn = Mid(AP_CMD2, 5, 9)
                                    DelayWrite = False
                                    IgnoreResp = True
                                    RaDecJ2000()
                                    LogScope("Status = ", Color.Black, "RA/DEC J2000 to J" & Yr)
                                    AP_CMD2_RA = ":Sr " & NewRA & "#"
                                    AP_CMD2_DEC = ":Sd " & NewDEC & "#"
                                    Resp_Length = 1
                                End If

                            Case Else
                                Resp_Req = False
                        End Select

                        ' special control characters in :G command (undocumented, found in ASCOM and PulseGuid software)
                        If Mid(AP_CMD2, 1, 2) = ":G" Then
                            Dim Cmd4 As String = Mid(AP_CMD2, 3, 1)
                            Select Case Cmd4

                                Case Chr(16)
                                    Resp_Length = 0
                                    Resp_Req = True

                                Case Chr(4)
                                    Resp_Length = 0
                                    Resp_Req = True

                                Case Chr(23)
                                    Resp_Length = 0
                                    Resp_Req = True

                                Case Chr(18)
                                    Resp_Length = 0
                                    Resp_Req = True

                                Case Chr(5)
                                    Resp_Length = 0
                                    Resp_Req = True

                                Case Chr(21)
                                    Resp_Length = 0
                                    Resp_Req = True

                            End Select

                        End If

                        If J2000Resp = False Then
                            If Resp_Req = False Then
                                LogScope("Rec2 < ", Color.DarkViolet, AP_CMD2)
                                SendReceiveAP(AP_CMD2, Msg, False, 0)
                            Else
                                LogScope("Rec2 < ", Color.DarkViolet, AP_CMD2)
                                If DelayWrite = False Then
                                    If IgnoreResp = False Then
                                        SendReceiveAP(AP_CMD2, Msg, True, Resp_Length)
                                        SerialPort2.Write(Rsp)
                                        LogScope("Sent2 > ", Color.DarkMagenta, Rsp)
                                    Else
                                        SendReceiveAP(AP_CMD2_RA, Msg, True, Resp_Length)
                                        SendReceiveAP(AP_CMD2_DEC, Msg, True, Resp_Length)
                                        SerialPort2.Write("1")
                                        LogScope("Sent2 > ", Color.DarkMagenta, "1")
                                    End If
                                Else
                                    SerialPort2.Write(Rsp)
                                    LogScope("Sent2D > ", Color.DarkMagenta, Rsp)
                                End If
                            End If
                        Else
                            ' Convert RA/DEC from Current JD to J2000
                            Select Case Cmd3
                                Case ":GR"
                                    SendReceiveAP(":GR#", Msg, True, Resp_Length)
                                    AP_RSP2_RA = Rsp
                                    RaIn = Rsp
                                    SendReceiveAP(":GD#", Msg, True, Resp_Length)
                                    AP_RSP2_DEC = Rsp
                                    DecIn = Rsp
                                    RaDecToJ2000()
                                    AP_RSP2_RA = NewRA & "#"
                                    SerialPort2.Write(AP_RSP2_RA)
                                    LogScope("Sent2 J2000 > ", Color.DarkMagenta, AP_RSP2_RA)
                                    J2000IgnoreDEC = True

                                Case ":GD"
                                    If J2000IgnoreDEC = True Then
                                        AP_RSP2_DEC = NewDEC & "#"
                                        SerialPort2.Write(AP_RSP2_DEC)
                                        LogScope("Sent2 J2000 > ", Color.DarkMagenta, AP_RSP2_DEC)
                                        J2000IgnoreDEC = False
                                    End If

                            End Select
                        End If

                    End If
                End If

            Next

            ' clear indata after processing
            InData2 = PartCmd
            InBuf2Len = PartCmd.Length

        End If

    End Sub

    Private Sub ToolStripMenuItemRDadjust_Click(sender As System.Object, e As System.EventArgs) Handles ToolStripMenuItemRDadjust.Click
        If ToolStripMenuItemRDadjust.Checked = True Then
            ToolStripMenuItemRDadjust.Checked = False
        Else
            ToolStripMenuItemRDadjust.Checked = True
        End If

    End Sub

    Private Sub ButtonRADEC_Click(sender As System.Object, e As System.EventArgs) Handles ButtonRADEC.Click
        Form_RA_DEC.Show()
        Form_RA_DEC.Focus()

    End Sub

    Private Sub ButtonALTAZ_Click(sender As System.Object, e As System.EventArgs) Handles ButtonALTAZ.Click
        Form_AZ_EL.Show()
        Form_AZ_EL.Focus()

    End Sub

    Public Sub ShowTheCOMports()
        Dim I, J, J2 As Integer

        If IgnoreButton = False Then
            Form_COM_PORTS.ListBox1.Items.Clear()
            SerialPortNameList.Clear()
            J = ToolStripComboBoxCom.SelectedIndex
            J2 = ComboBoxCom2.SelectedIndex
            BuildSerialPortComboBox()
            ToolStripComboBoxCom.SelectedIndex = J
            ComboBoxCom2.SelectedIndex = J2
            For I = 0 To SerialPortNameList.Count - 1
                Form_COM_PORTS.ListBox1.Items.Add(SerialPortNameList(I))
            Next
            Form_COM_PORTS.Show()
            Form_COM_PORTS.Focus()
        End If

    End Sub

    Private Sub GetALT_Click(sender As System.Object, e As System.EventArgs)
        SendReceiveAP(":GA#", "ALT", True, 0)
        Status = "Telescope ALT: " & Rsp
        StatusLabel.Text = Status

    End Sub

    Private Sub GetAZ_Click(sender As System.Object, e As System.EventArgs)
        SendReceiveAP(":GZ#", "AZ", True, 0)
        Status = "Telescope AZ: " & Rsp
        StatusLabel.Text = Status

    End Sub

    Private Sub MeridianOffsetButton_Click(sender As System.Object, e As System.EventArgs) Handles MeridianOffsetButton.Click
        Form_Meridian.Show()

    End Sub

    Private Sub SettingsMenu_Click(sender As System.Object, e As System.EventArgs) Handles SettingsMenu.Click
        Form_ControlP.Show()

    End Sub

    Private Sub DiagnosticsToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles DiagnosticsToolStripMenuItem.Click
        Form_DIAGS.Show()

    End Sub


    Private Sub CheckBoxDT_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxDT.CheckedChanged
        If Form_Dome.Visible = False And Form_Dome.FormLoading = True Then
            Form_Dome.Show()
            CheckBoxDT.Checked = False
        End If

        If Form_Dome.CheckBoxTrack.Enabled = True Then
            Form_Dome.CheckBoxTrack.Checked = CheckBoxDT.Checked
        Else : CheckBoxDT.Checked = False
        End If

    End Sub

    Private Sub xComboBoxFocuser_SelectedIndexChanged(sender As System.Object, e As System.EventArgs)
        ToolTip1.SetToolTip(ComboBoxFocuser, ComboBoxFocuser.SelectedItem)

    End Sub

    Private Sub ButtonFocus_Click(sender As System.Object, e As System.EventArgs) Handles ButtonFocus.Click
        Select Case ComboBoxFocuser.SelectedIndex
            Case 0
                If GroupBox1.Enabled = True Then
                    Form_FOCUS.Show()
                    Form_FOCUS.Focus()
                Else
                    StatusLabel.Text = "Not connected"
                End If

            Case 1
                Form_FocusAGF.Show()
                Form_FocusAGF.Focus()

            Case 2
                Form_FocusML.Show()
                Form_FocusML.Focus()

            Case 3
                Form_FocusASCOM2.Show()
                Form_FocusASCOM2.Focus()
        End Select

    End Sub

    Private Sub ComboBoxFocuser_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBoxFocuser.SelectedIndexChanged
        ToolTip1.SetToolTip(ComboBoxFocuser, ComboBoxFocuser.SelectedItem)

    End Sub

    Private Sub ButtonSetSlewRateContext_Click(sender As System.Object, e As System.EventArgs) Handles ButtonSetSlewRateContext.Click
        Dim Slew_Rate As String = ""
        Dim Slew_Cmd As String = ""

        Select Case ToolStripComboBox1.SelectedIndex
            Case 0
                Slew_Cmd = ":RS0#"
                Slew_Rate = "600x"
            Case 1
                Slew_Cmd = ":RS1#"
                Slew_Rate = "900x"
            Case 2
                Slew_Cmd = ":RS2#"
                Slew_Rate = "1200x"
        End Select

        SendReceiveAP(Slew_Cmd, "Slew Rate", False, 0)
        StatusLabel.Text = "Slew rate set to " & Slew_Rate

    End Sub

    Private Sub PictureBoxStopTimer_Click(sender As System.Object, e As System.EventArgs) Handles PictureBoxStopTimer.Click
        Form_ControlP.TabControlP.SelectedIndex = 2
        Form_ControlP.Show()

    End Sub

End Class


Public Class KeyButton
    Inherits System.Windows.Forms.Button
    Public Sub New()
        MyBase.New()
    End Sub

    Protected Overrides Function IsInputKey(ByVal keyData As System.Windows.Forms.Keys) As Boolean
        Return True
    End Function
End Class