Imports System.Windows.Threading
Imports System.Collections.ObjectModel
Imports System.IO
Imports EgtUILib
Imports EgtWPFLib

Public Class AlarmsPageUC

   ' Riferimento alla MainWindow
   Private m_MainWindow As MainWindow = DirectCast(Application.Current.MainWindow, MainWindow)
   Private m_CurrentMachine As CurrentMachine
   Friend m_CN As CN_generico

   ' Definizione pagina attrezzaggio
   Friend m_SetUpPage As SetUpPage
   ' Properties
   Private m_bFirst As Boolean = True

   'Lista che contiene le lame disponibili (per Combobox pagina Alarms)
   Private m_SawList As New ObservableCollection(Of String)
   Private m_DrillList As New ObservableCollection(Of String)
   Private m_MillList As New ObservableCollection(Of String)
   Private m_CupWheelList As New ObservableCollection(Of String)
   Private m_WaterJetList As New ObservableCollection(Of String)
   Private m_AuxToolTypeList As New List(Of StringIdCmBx)

   ' Costante per nessun utensile definito
   Private Const NO_TOOL As String = "-----"

   Private Sub AlarmsPage_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized

      'Assegno liste a combobox
      CurrSawCmBx.ItemsSource = m_SawList
      CurrDrillCmBx.ItemsSource = m_DrillList
      CurrMillCmBx.ItemsSource = m_MillList
      CurrCupWheelCmBx.ItemsSource = m_CupWheelList
      CurrWJetCmBx.ItemsSource = m_WaterJetList
      AuxiliaryToolCmBx.ItemsSource = m_AuxToolTypeList

      ' Assegno lista ad elenco materiali
      MaterialsLstBx.ItemsSource = m_MainWindow.m_CurrentMachine.Materials

      ' Se non è impostato il controllo numerico, nascondo il bottone di tastatura lama
      If GetPrivateProfileInt(S_NUMERICALCONTROL, K_TYPE, 0, m_MainWindow.GetMachIniFile()) = 0 Then
         SawProbingBtn.Visibility = Windows.Visibility.Hidden
      End If

      ' Imposto i messaggi letti dal file dei messaggi
      CurrSawTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 1)
      AuxiliaryToolTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 2)
      CurrDrillTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 3)
      CurrCupWheelTxBl.Text = EgtMsg(MSG_ALARMS2PAGEUC + 20)
      CurrMillTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 4)
      CurrWJetTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 0)
      HolesOffsetTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 9)
      HolesOverlapTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 10)
      HolesToleranceTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 11)
      OneHoleInCornerTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 26)
      CutExtraLenTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 6)
      AngleCutExtraLenTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 7)
      CompleteCutsTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 8)
      SafeZTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 5)
      MaterialsGpBx.Header = EgtMsg(MSG_ALARMSPAGEUC + 13)
      NewMatBtn.Content = EgtMsg(MSG_ALARMSPAGEUC + 14)
      RemoveMatBtn.Content = EgtMsg(MSG_ALARMSPAGEUC + 15)
      SetUpGpBx.Header = EgtMsg(MSG_ALARMSPAGEUC + 16)
      HolesGpBx.Header = EgtMsg(MSG_ALARMSPAGEUC + 17)
      ExtArcMinRadTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 18)
      IntArcMaxSideAngTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 24)
      PreCutExitTxBl.Text = EgtMsg(91065)                                ' PreTaglio uscite
      MachineParamGpBx.Header = EgtMsg(MSG_ALARMSPAGEUC + 19)
      SawGpBx.Header = EgtMsg(MSG_ALARMSPAGEUC + 25)
      DirectCutsParamGpBx.Header = EgtMsg(MSG_ALARMSPAGEUC + 27)         ' Tagli diretti
      FinalHomeTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 28)                 ' Home finale
      MillingsParamGpBx.Header = EgtMsg(MSG_ALARMSPAGEUC + 29)           ' Parametri fresature
      CornerCutsTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 44)                ' Sempre sugli angoli
      InternalCutsTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 30)              ' Sempre sugli interni
      ShortTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 49)                     ' Accorciamento
      TopMillGpBx.Header = EgtMsg( 91061)                                ' Parametri incisioni
      TmEnableTxBl.Text = EgtMsg( 91062)                                 ' Con fresa
      TmDepthTxBl.Text = EgtMsg( 91063)                                  ' Profondità
      TmWidthTxBl.Text = EgtMsg( 91064)                                  ' Larghezza
      WJsParamGpBx.Header = EgtMsg( 91058)                               ' Parametri waterjet
      WjIntCutsTxBl.Text = EgtMsg( 90930)                                ' Sempre sugli interni
      NestingParamGpBx.Header = EgtMsg(MSG_ALARMSPAGEUC + 31)            ' Nesting
      AlignTxBl.Text = EgtMsg(90932)                                     ' Allineato
      GhigliottinaTxBl.Text = EgtMsg(91066)                              ' Ghigliottina
      AutomaticTxBl.Text = EgtMsg(91059)                                 ' Automatico
      SetUpBtn.Content = EgtMsg(MSG_ALARMSPAGEUC + 33)                   ' Attrezzaggio
      NewMatBtn.Content = EgtMsg(MSG_ALARMSPAGEUC + 34)                  ' Nuovo
      RemoveMatBtn.Content = EgtMsg(MSG_ALARMSPAGEUC + 35)               ' Elimina
      AdditionalTableTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 36)           ' Altezza sovratavola
      AutoRawImageParamGpBx.Header = EgtMsg(MSG_ALARMSPAGEUC + 37)       ' Contorno da Foto
      BackImageBtn.Content = EgtMsg(MSG_ALARMSPAGEUC + 38)               ' Sfondo
      ThresholdTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 39)                 ' Soglia
      ToleranceTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 40)                 ' Tolleranza
      WashingTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 41)                   ' Lavaggio
      SideAngCutProbeTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 50)           ' Tastatura tagli inclinati
      CutFredGpBx.Header = EgtMsg(MSG_ALARMSPAGEUC + 46)                 ' Tagli Feed inizio/fine
      CfrLenTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 47)                    ' Lunghezza
      CfrPercTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 48)                   ' Riduzione %
      MachiningsGpBx.Header = EgtMsg(MSG_ALARMS2PAGEUC + 1)              ' Lavorazioni
      CurrSawingTxBl.Text = EgtMsg(MSG_ALARMS2PAGEUC + 2)                ' Taglio lama
      CurrDrillingTxBl.Text = EgtMsg(MSG_ALARMS2PAGEUC + 3)              ' Foratura
      CurrMillingTxBl.Text = EgtMsg(MSG_ALARMS2PAGEUC + 4)               ' Fresatura
      CurrPocketingTxBl.Text = EgtMsg(91069)                             ' Svuotatura
      CurrWaterJettingTxBl.Text = EgtMsg(MSG_ALARMS2PAGEUC + 7)          ' WaterJet
      CurrDripSawingTxBl.Text = EgtMsg(MSG_ALARMS2PAGEUC + 5)            ' DripSawing
      CurrDripDrillingTxBl.Text = EgtMsg(MSG_ALARMS2PAGEUC + 6)          ' DripDrilling
      FrameGpBx.Header = EgtMsg(91068)                                   ' Cornici
      FramePauseTxBl.Text = EgtMsg(91067)                                ' Inserisci pausa
      UseLaserOriginTxBl.Text = EgtMsg(91129)                            ' Usa laser per origine
      AutoRawImageParamGpBx.Visibility = Windows.Visibility.Hidden
   End Sub

   Private Sub AlarmsPage_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded

      If m_bFirst Then
         ' Variabile che accorcia il riferimento alla macchina corrente
         m_CurrentMachine = m_MainWindow.m_CurrentMachine

         ' in assenza dell'uscita H1 nascondo i parametri lama
         If EgtGetHeadId("H1") = GDB_ID.NULL Then
            SawGpBx.Visibility = Visibility.Hidden
            TopMillGpBx.Visibility = Visibility.Hidden
            CurrSawTxBl.Visibility = Visibility.Hidden
            CurrSawCmBx.Visibility = Visibility.Hidden
         End If

         ' Verifico la configurazione della macchina per creare i combobox
         Select Case m_CurrentMachine.MountedToolConfig
            Case CurrentMachine.MountedToolConfigs.SAW
               ' Elimino le righe inutili e riduco il groupbox utensili correnti
               For Index As Integer = 7 - 1 To 2 Step -1
                  CurrToolsGrid.RowDefinitions.RemoveAt(Index)
               Next
               Dim EndRow As New RowDefinition
               EndRow.Height = New GridLength(0.25, GridUnitType.Star)
               CurrToolsGrid.RowDefinitions.Add(EndRow)
               SetUpGpBx.SetValue(Grid.RowSpanProperty, 1)
               ' Disattivo il gruppo dei parametri fori
               HolesGpBx.Visibility = Windows.Visibility.Hidden
            Case CurrentMachine.MountedToolConfigs.SAWANDAUXTOOL
            'Non faccio alcunchè
            Case CurrentMachine.MountedToolConfigs.MANUALTOOLCHANGER, CurrentMachine.MountedToolConfigs.TOOLCHANGER
               'Da implementare
         End Select

         ' Se non previste forature, disabilito relativo box
         If Not m_CurrentMachine.bDrilling Then
            HolesGpBx.Visibility = Visibility.Hidden
         End If

         ' Se non previste fresature, disabilito relativo box e uso fresa con incisione
         If Not m_CurrentMachine.bMilling Then
            MillingsParamGpBx.Visibility = Visibility.Hidden
            TmEnableChBx.IsEnabled = False
            TmEnableChBx.IsChecked = False
         End If

         ' Se non previsti tagli waterjet, disabilito relativo box
         If Not m_CurrentMachine.bWaterJetting Then
            WjsParamGpBx.Visibility = Visibility.Hidden
         End If

         ' Abilitazione box per contorni grezzo da foto
         If m_MainWindow.m_Camera.GetCalcContour() Then
            AutoRawImageParamGpBx.Visibility = Windows.Visibility.Visible
            ' Se macchina fotografica disabilitata, disabilito scatto per sfondo
            If Not m_MainWindow.m_Camera.GetCameraLink() Then
               BackImageBtn.IsEnabled = False
            End If
         End If

         ' Abilitazione Feed ridotta su inizio/fine tagli
         If m_CurrentMachine.bFsevEnable And EgtGetHeadId("H1") <> GDB_ID.NULL Then
            CutFredGpBx.Visibility = Windows.Visibility.Visible
         Else
            CutFredGpBx.Visibility = Windows.Visibility.Hidden
         End If

         ' Se non previsto nesting automatico, nascondo flag relativo
         If Not m_MainWindow.GetAutoNestingOption() Then
            AutomaticTxBl.Visibility = Visibility.Hidden
            AutomaticChBx.Visibility = Visibility.Hidden
         End If

         m_bFirst = False
      End If

         ' Aggiorno lista delle lame per pagina macchina in cui scegliere quella corrente
         CreateToolList(MCH_TF.SAWBLADE, m_SawList)
      ' Seleziono lama corrente
      CurrSawCmBx.SelectedItem = m_CurrentMachine.sCurrSaw

      ' nascondo la lista dei materiali solo se macchina WaterJet
      If m_CurrentMachine.bWaterJet Then
         MaterialsGpBx.Visibility = Visibility.Hidden
      End If

      ' Verifico la configurazione della macchina per creare i combobox
      Select Case m_CurrentMachine.MountedToolConfig
         Case CurrentMachine.MountedToolConfigs.SAW
            ' Non compio alcuna azione (non sono previsti utensili ausiliari)

         Case CurrentMachine.MountedToolConfigs.SAWANDAUXTOOL
            m_AuxToolTypeList.Clear()
            ' creo l'elenco degli utensili ausiliri
            If m_CurrentMachine.bDrill Then
               m_AuxToolTypeList.Add(New StringIdCmBx(1, EgtMsg(MSG_ALARMSPAGEUC + 21)))      ' Foretto
            End If
            If m_CurrentMachine.bMill Then
               m_AuxToolTypeList.Add(New StringIdCmBx(2, EgtMsg(MSG_ALARMSPAGEUC + 22)))      ' Fresa
            End If
            If m_CurrentMachine.bCupWheel Then
               m_AuxToolTypeList.Add(New StringIdCmBx(3, EgtMsg(MSG_TOOLSDBPAGEUC + 34)))     ' Mola da scasso
            End If
            If m_CurrentMachine.bWaterJet Then
               m_AuxToolTypeList.Add(New StringIdCmBx(4, EgtMsg(MSG_TOOLSDBPAGEUC + 35)))     ' WaterJet
            End If
            ' Aggiungo elemento nessuno in fondo alla lista
            m_AuxToolTypeList.Add(New StringIdCmBx(0, EgtMsg(MSG_ALARMSPAGEUC + 20)))         ' Nessuno

            ' ComboBox per la selezione dell'utensile ausiliario
            AuxiliaryToolTxBl.Visibility = Windows.Visibility.Visible
            AuxiliaryToolCmBx.Visibility = Windows.Visibility.Visible
            ' Drilling
            CurrDrillTxBl.Visibility = Windows.Visibility.Hidden
            CurrDrillCmBx.Visibility = Windows.Visibility.Hidden
            ' Milling
            CurrMillTxBl.Visibility = Windows.Visibility.Hidden
            CurrMillCmBx.Visibility = Windows.Visibility.Hidden
            ' Pocketing
            CurrCupWheelTxBl.Visibility = Windows.Visibility.Hidden
            CurrCupWheelCmBx.Visibility = Windows.Visibility.Hidden
            ' WaterJet
            CurrWJetTxBl.Visibility = Windows.Visibility.Hidden
            CurrWJetCmBx.Visibility = Windows.Visibility.Hidden

            ' verifico quale utensile è attulamente "montato sulla macchina"
            If m_CurrentMachine.sCurrDrill <> String.Empty Then
               CreateToolList(MCH_TF.DRILLBIT, m_DrillList)
               m_DrillList.Add(NO_TOOL)
               CurrDrillCmBx.SelectedItem = m_CurrentMachine.sCurrDrill
               AuxiliaryToolCmBx.SelectedItem = StringIdCmBx.FromIdToStringIdCmBx(1, m_AuxToolTypeList)
               CurrDrillTxBl.Visibility = Windows.Visibility.Visible
               CurrDrillCmBx.Visibility = Windows.Visibility.Visible
            ElseIf m_CurrentMachine.sCurrMill <> String.Empty Then
               CreateToolList(MCH_TF.MILL, MCH_TY.MILL_STD, m_MillList)
               m_MillList.Add(NO_TOOL)
               CurrMillCmBx.SelectedItem = m_CurrentMachine.sCurrMill
               AuxiliaryToolCmBx.SelectedItem = StringIdCmBx.FromIdToStringIdCmBx(2, m_AuxToolTypeList)
               CurrMillTxBl.Visibility = Windows.Visibility.Visible
               CurrMillCmBx.Visibility = Windows.Visibility.Visible
            ElseIf m_CurrentMachine.sCurrMillNoTip <> String.Empty Then
               CreateToolList(MCH_TF.MILL, MCH_TY.MILL_NOTIP, m_CupWheelList)
               m_CupWheelList.Add(NO_TOOL)
               CurrCupWheelCmBx.SelectedItem = m_CurrentMachine.sCurrMillNoTip
               AuxiliaryToolCmBx.SelectedItem = StringIdCmBx.FromIdToStringIdCmBx(3, m_AuxToolTypeList)
               CurrCupWheelTxBl.Visibility = Windows.Visibility.Visible
               CurrCupWheelCmBx.Visibility = Windows.Visibility.Visible
            ElseIf m_CurrentMachine.sCurrWaterJet <> String.Empty Then
               CreateToolList(MCH_TF.WATERJET, m_WaterJetList)
               m_WaterJetList.Add(NO_TOOL)
               CurrWJetCmBx.SelectedItem = m_CurrentMachine.sCurrWaterJet
               AuxiliaryToolCmBx.SelectedItem = StringIdCmBx.FromIdToStringIdCmBx(4, m_AuxToolTypeList)
               CurrWJetTxBl.Visibility = Windows.Visibility.Visible
               CurrWJetCmBx.Visibility = Windows.Visibility.Visible
            Else
               AuxiliaryToolCmBx.SelectedItem = StringIdCmBx.FromIdToStringIdCmBx(0, m_AuxToolTypeList)
            End If

         Case CurrentMachine.MountedToolConfigs.MANUALTOOLCHANGER, CurrentMachine.MountedToolConfigs.TOOLCHANGER
            ' attivo il bottone per l'apertura della pagina che mostra la configurazione degli utensili in parcheggio
            SetUpBtn.Visibility = Windows.Visibility.Visible

      End Select

      ' aggiorno le TextBlock con le lavorazioni correnti
      RefreschMachining()

      ' Leggo offset fori
      Dim dVal As Double
      dVal = GetPrivateProfileDouble(S_MACH_NEST, K_MACH_HOLES_OFFSET, 0, m_MainWindow.GetMachIniFile())
      EgtMdbSetGeneralParam(MCH_GP.EXTRARONDRIREG, dVal)
      HolesOffsetTxBx.Text = LenToString(dVal, 2)
      ' Leggo sovrapposizione fori
      dVal = GetPrivateProfileDouble(S_MACH_NEST, K_MACH_HOLES_OVERLAP, 0, m_MainWindow.GetMachIniFile())
      HolesOverlapTxBx.Text = LenToString(dVal, 2)
      ' Leggo tolleranza diametro fori
      dVal = GetPrivateProfileDouble(S_MACH_NEST, K_MACH_HOLES_DIAMTOLER, 0, m_MainWindow.GetMachIniFile())
      EgtMdbSetGeneralParam(MCH_GP.HOLEDIAMTOLER, dVal)
      HolesToleranceTxBx.Text = LenToString(dVal, 2)
      ' Leggo un solo foro in corner
      OneHoleInCornerChBx.IsChecked =
             (GetPrivateProfileInt(S_MACH_NEST, K_MACH_ONEHOLE_INTCORNER, 0, m_MainWindow.GetMachIniFile()) <> 0)
      ' Leggo sicurezza su tagli
      dVal = GetPrivateProfileDouble(S_MACH_NEST, K_MACH_SAFE_LEN_CUT, 0, m_MainWindow.GetMachIniFile())
      EgtMdbSetGeneralParam(MCH_GP.EXTRALONCUTREG, dVal)
      CutExtraLenTxBx.Text = LenToString(dVal, 2)
      ' Leggo sicurezza su tagli in angoli interni
      dVal = GetPrivateProfileDouble(S_MACH_NEST, K_MACH_SAFE_LEN_INTCORNER, 0, m_MainWindow.GetMachIniFile())
      AngleCutExtraLenTxBx.Text = LenToString(dVal, 2)
      ' Leggo distanza di sicurezza
      dVal = 0
      EgtMdbGetGeneralParam(MCH_GP.SAFEZ, dVal)
      SafeZTxBx.Text = LenToString(dVal, 2)
      ' Leggo raggio minimo arco esterno
      dVal = GetPrivateProfileDouble(S_MACH_NEST, K_MACH_EXTARCMINRAD, 200, m_MainWindow.GetMachIniFile())
      EgtMdbSetGeneralParam(MCH_GP.EXTSAWARCMINRAD, dVal)
      ExtArcMinRadTxBx.Text = LenToString(dVal, 2)
      ' Leggo se PreCutExit attivo (per taglio ceramico)
      Dim nPreCutExit As Integer = GetPrivateProfileInt(S_MACH_NEST, K_MACH_PRECUTEXIT, -1, m_MainWindow.GetMachIniFile())
      If nPreCutExit = -1 Then
         PreCutExitTxBl.Visibility = Visibility.Hidden
         PreCutExitChBx.Visibility = Visibility.Hidden
      Else
         PreCutExitChBx.IsChecked = ( nPreCutExit <> 0)
      End If
      ' Leggo angolo di fianco massimo arco interno
      dVal = GetPrivateProfileDouble(S_MACH_NEST, K_MACH_INTARCMAXSIDEANG, 45, m_MainWindow.GetMachIniFile())
      EgtMdbSetGeneralParam(MCH_GP.INTSAWARCMAXSIDEANG, dVal)
      IntArcMaxSideAngTxBx.Text = DoubleToString(dVal, 2)
      ' Salvo DB lavorazioni con aggiornamenti parametri generali
      EgtMdbSave()
      ' Leggo lavorazione angoli con fresa
      CornerCutsChBx.IsChecked =
             (GetPrivateProfileInt(S_MACH_NEST, K_MACH_MILLING_ON_CORNERS, 1, m_MainWindow.GetMachIniFile()) <> 0)
      ' Leggo lavorazione interni con fresa
      InternalCutsChBx.IsChecked =
             (GetPrivateProfileInt(S_MACH_NEST, K_MACH_MILLING_ON_SINKS, 0, m_MainWindow.GetMachIniFile()) <> 0)
      WjIntCutsChBx.IsChecked =
             (GetPrivateProfileInt(S_MACH_NEST, K_MACH_MILLING_ON_SINKS, 0, m_MainWindow.GetMachIniFile()) <> 0)
      ' Leggo accorciamento angoli con fresa
      dVal = GetPrivateProfileDouble(S_MACH_NEST, K_MACH_MILLING_SHORTENING, 0, m_MainWindow.GetMachIniFile())
      ShortTxBx.Text = LenToString(dVal, 2)
      ' Leggo flag abilitazione incisioni con fresa
      TmEnableChBx.IsChecked =
             (GetPrivateProfileInt(S_MACH_NEST, K_MACH_ENGRAVING_WITHMILL, 1, m_MainWindow.GetMachIniFile()) <> 0)
      ' Leggo profondità e larghezza incisioni
      dVal = GetPrivateProfileDouble(S_MACH_NEST, K_MACH_ENGRAVING_DEPTH, 0, m_MainWindow.GetMachIniFile())
      TmDepthTxBx.Text = LenToString(dVal, 2)
      dVal = GetPrivateProfileDouble(S_MACH_NEST, K_MACH_ENGRAVING_WIDTH, 0, m_MainWindow.GetMachIniFile())
      TmWidthTxBx.Text = LenToString(dVal, 2)
      ' Flag per movimento in home alla fine dei tagli diretti
      FinalHomeChBx.IsChecked = m_MainWindow.m_CurrentMachine.bDirectCutsFinalHome
      ' Leggo tagli ridotti per interferenza in nesting
      CompleteCutsChBx.IsChecked =
             (GetPrivateProfileInt(S_MACH_NEST, K_MACH_REDUCEDCUT, 0, m_MainWindow.GetMachIniFile()) = 0)
      ' Flag per nesting allineato
      AlignChBx.IsChecked =
             (GetPrivateProfileInt(S_MACH_NEST, K_MACH_NEST_ALIGNED, 0, m_MainWindow.GetMachIniFile()) <> 0)
      ' Flag per nesting a ghigliottina
      GhigliottinaChBx.IsChecked =
             (GetPrivateProfileInt(S_MACH_NEST, K_MACH_NEST_GHIGLIOTTINA, 0, m_MainWindow.GetMachIniFile()) <> 0)
      ' Flag per nesting automatico
      AutomaticChBx.IsChecked =
             (GetPrivateProfileInt(S_NEST, K_AUTOMATICOPTIMIZE, 0, m_MainWindow.GetIniFile()) <> 0)
      AdjustGhigliottinaTextOnAutomaticOrCompleteCuts()
      ' Flag per inserire la puasa dopo la sgrossatura delle cornici
      FramePauseChBx.IsChecked =
         (GetPrivateProfileInt(S_MACH_FRAME, K_MACH_PAUSE, 1, m_MainWindow.GetMachIniFile()) <> 0)
      ' Aggiorno messaggio sovratavola con numero tavola
      If GetTableCount() > 1 Then
         AdditionalTableTxBl.Text = EgtMsg(MSG_ALARMSPAGEUC + 36) & " " & GetCurrentTable().ToString()
      End If
      ' Leggo altezza sovratavola
      dVal = m_MainWindow.m_CurrentMachine.dAdditionalTable
      AdditionalTableTxBx.Text = LenToString(dVal, 2)
      ' Leggo soglia e tolleranza per contorno grezzo da foto
      ThresholdTxBx.Text = m_MainWindow.m_Camera.Threshold.ToString()
      dVal = m_MainWindow.m_Camera.Tolerance
      ToleranceTxBx.Text = LenToString(dVal, 2)
      ' Leggo flag tastatura tagli inclinati
      Dim nSacProbe As Integer = GetPrivateProfileInt(S_MACH_NEST, K_MACH_SACPROBE, -1, m_MainWindow.GetMachIniFile())
      If nSacProbe = -1 Then
         SideAngCutProbeGpBx.Visibility = Visibility.Hidden
      Else
         SideAngCutProbeChBx.IsChecked = (nSacProbe <> 0)
      End If
      ' Leggo flag lavaggio
      Dim nWashing As Integer = GetPrivateProfileInt(S_MACH_NEST, K_MACH_WASHING, -1, m_MainWindow.GetMachIniFile())
      If nWashing = -1 Then
         WashingGpBx.Visibility = Visibility.Hidden
      Else
         WashingChBx.IsChecked = ( nWashing <> 0)
      End If
      ' Leggo parametri per variazione feed in tagli
      CfrLenTxBx.Text = LenToString(m_CurrentMachine.dFsevLength, 3)
      CfrPercTxBx.Text = DoubleToString(m_CurrentMachine.dFsevPerc, 0)

      ' leggo flag per tavola definita da laser
      Dim nUseLaserOrigin As Integer = GetPrivateProfileInt(S_TABLE, K_USELASERORIGIN, -1, m_MainWindow.GetMachIniFile())
      If nUseLaserOrigin = -1 Then
         UseLaserOriginTxBl.Visibility = Visibility.Hidden
         UseLaserOriginChBx.Visibility = Visibility.Hidden
      Else
         UseLaserOriginTxBl.Visibility = Visibility.Visible
         UseLaserOriginChBx.IsChecked = (nUseLaserOrigin <> 0)
      End If

   End Sub

   ' aggiorna le text delle lavorazioni (la selezione avviene nella pagina del grezzo o dalla pagina del progetto corrente)
   Private Sub RefreschMachining()
      If m_CurrentMachine.sCurrSawing <> String.Empty Then
         CurrSawingTxBx.Text = m_CurrentMachine.sCurrSawing
         CurrSawingTxBl.Visibility = Windows.Visibility.Visible
         CurrSawingTxBx.Visibility = Windows.Visibility.Visible
      Else
         CurrSawingTxBl.Visibility = Windows.Visibility.Hidden
         CurrSawingTxBx.Visibility = Windows.Visibility.Hidden
      End If
      If m_CurrentMachine.sCurrDrilling <> String.Empty Then
         CurrDrillingTxBx.Text = m_CurrentMachine.sCurrDrilling
         CurrDrillingTxBl.Visibility = Windows.Visibility.Visible
         CurrDrillingTxBx.Visibility = Windows.Visibility.Visible
      Else
         CurrDrillingTxBl.Visibility = Windows.Visibility.Hidden
         CurrDrillingTxBx.Visibility = Windows.Visibility.Hidden
      End If
      If m_CurrentMachine.sCurrMilling <> String.Empty Then
         CurrMillingTxBx.Text = m_CurrentMachine.sCurrMilling
         CurrMillingTxBl.Visibility = Windows.Visibility.Visible
         CurrMillingTxBx.Visibility = Windows.Visibility.Visible
      Else
         CurrMillingTxBl.Visibility = Windows.Visibility.Hidden
         CurrMillingTxBx.Visibility = Windows.Visibility.Hidden
      End If
      If m_CurrentMachine.sCurrPocketing <> String.Empty Then
         CurrPocketingTxBx.Text = m_CurrentMachine.sCurrPocketing
         CurrPocketingTxBl.Visibility = Windows.Visibility.Visible
         CurrPocketingTxBx.Visibility = Windows.Visibility.Visible
      Else
         CurrPocketingTxBl.Visibility = Windows.Visibility.Hidden
         CurrPocketingTxBx.Visibility = Windows.Visibility.Hidden
      End If
      If m_CurrentMachine.sCurrWaterJetting <> String.Empty Then
         CurrWaterJettingTxBx.Text = m_CurrentMachine.sCurrWaterJetting
         CurrWaterJettingTxBl.Visibility = Windows.Visibility.Visible
         CurrWaterJettingTxBx.Visibility = Windows.Visibility.Visible
         If m_MainWindow.m_CurrentMachine.bFromDBWaterJet Then
            CurrWaterJettingTxBx.SetValue(Grid.ColumnSpanProperty, 1)
            CurrWaterJettingTxBx.SetValue(MarginProperty, New Thickness(CurrWaterJettingTxBx.Margin.Left,
                                                                        CurrWaterJettingTxBx.Margin.Top,
                                                                        5,
                                                                        CurrWaterJettingTxBx.Margin.Bottom))
            CurrWaterJettingQualityTxBx.Text = m_CurrentMachine.sCurrWaterJettingQuality
            CurrWaterJettingQualityTxBx.Visibility = Windows.Visibility.Visible
         Else
            CurrWaterJettingTxBx.SetValue(Grid.ColumnSpanProperty, 2)
            CurrWaterJettingTxBx.SetValue(MarginProperty, New Thickness(CurrWaterJettingTxBx.Margin.Left,
                                                                        CurrWaterJettingTxBx.Margin.Top,
                                                                        10,
                                                                        CurrWaterJettingTxBx.Margin.Bottom))
            CurrWaterJettingQualityTxBx.Visibility = Windows.Visibility.Collapsed
         End If
      Else
         CurrWaterJettingTxBl.Visibility = Windows.Visibility.Hidden
         CurrWaterJettingTxBx.Visibility = Windows.Visibility.Hidden
         CurrWaterJettingQualityTxBx.Visibility = Windows.Visibility.Hidden
      End If
      If m_CurrentMachine.sCurrDripSawing <> String.Empty Then
         CurrDripSawingTxBx.Text = m_CurrentMachine.sCurrDripSawing
         CurrDripSawingTxBl.Visibility = Windows.Visibility.Visible
         CurrDripSawingTxBx.Visibility = Windows.Visibility.Visible
      Else
         CurrDripSawingTxBl.Visibility = Windows.Visibility.Hidden
         CurrDripSawingTxBx.Visibility = Windows.Visibility.Hidden
      End If
      If m_CurrentMachine.sCurrDripDrilling <> String.Empty Then
         CurrDripDrillingTxBx.Text = m_CurrentMachine.sCurrDripDrilling
         CurrDripDrillingTxBl.Visibility = Windows.Visibility.Visible
         CurrDripDrillingTxBx.Visibility = Windows.Visibility.Visible
      Else
         CurrDripDrillingTxBl.Visibility = Windows.Visibility.Hidden
         CurrDripDrillingTxBx.Visibility = Windows.Visibility.Hidden
      End If
   End Sub

   ' questo metodo è utilizzato solo per le macchine con utensile ausiliario (Assenza del bottone Attrezzaggio-> monta un solo utensila per volta
   Private Sub AuxiliaryToolCmBx_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles AuxiliaryToolCmBx.SelectionChanged
      CurrDrillTxBl.Visibility = Windows.Visibility.Hidden
      CurrDrillCmBx.Visibility = Windows.Visibility.Hidden
      CurrMillTxBl.Visibility = Windows.Visibility.Hidden
      CurrMillCmBx.Visibility = Windows.Visibility.Hidden
      CurrCupWheelTxBl.Visibility = Windows.Visibility.Hidden
      CurrCupWheelCmBx.Visibility = Windows.Visibility.Hidden
      CurrWJetTxBl.Visibility = Windows.Visibility.Hidden
      CurrWJetCmBx.Visibility = Windows.Visibility.Hidden
      Dim SelectedItem As StringIdCmBx = AuxiliaryToolCmBx.SelectedItem
      Select Case SelectedItem.nId
         Case 0
            m_CurrentMachine.sCurrDrill = String.Empty
            m_CurrentMachine.sCurrMill = String.Empty
         Case 1
            CreateToolList(MCH_TF.DRILLBIT, m_DrillList)
            m_DrillList.Add(NO_TOOL)
            If m_CurrentMachine.sCurrDrill = String.Empty Then
               CurrDrillCmBx.SelectedItem = NO_TOOL
            Else
               CurrDrillCmBx.SelectedItem = m_CurrentMachine.sCurrDrill
            End If
            m_CurrentMachine.sCurrMill = String.Empty
            m_CurrentMachine.sCurrMilling = String.Empty
            m_CurrentMachine.sCurrMillNoTip = String.Empty
            m_CurrentMachine.sCurrPocketing = String.Empty
            m_CurrentMachine.sCurrWaterJet = String.Empty
            m_CurrentMachine.sCurrWaterJetting = String.Empty
            CurrDrillTxBl.Visibility = Windows.Visibility.Visible
            CurrDrillCmBx.Visibility = Windows.Visibility.Visible
         Case 2
            CreateToolList(MCH_TF.MILL, MCH_TY.MILL_STD, m_MillList)
            m_MillList.Add(NO_TOOL)
            If m_CurrentMachine.sCurrMill = String.Empty Then
               CurrMillCmBx.SelectedItem = NO_TOOL
            Else
               CurrMillCmBx.SelectedItem = m_CurrentMachine.sCurrMill
            End If
            m_CurrentMachine.sCurrDrill = String.Empty
            m_CurrentMachine.sCurrDrilling = String.Empty
            m_CurrentMachine.sCurrMillNoTip = String.Empty
            m_CurrentMachine.sCurrPocketing = String.Empty
            m_CurrentMachine.sCurrWaterJet = String.Empty
            m_CurrentMachine.sCurrWaterJetting = String.Empty
            CurrMillTxBl.Visibility = Windows.Visibility.Visible
            CurrMillCmBx.Visibility = Windows.Visibility.Visible
         Case 3
            CreateToolList(MCH_TF.MILL, MCH_TY.MILL_NOTIP, m_CupWheelList)
            m_CupWheelList.Add(NO_TOOL)
            If m_CurrentMachine.sCurrMillNoTip = String.Empty Then
               CurrCupWheelCmBx.SelectedItem = NO_TOOL
            Else
               CurrCupWheelCmBx.SelectedItem = m_CurrentMachine.sCurrMillNoTip
            End If
            m_CurrentMachine.sCurrDrill = String.Empty
            m_CurrentMachine.sCurrDrilling = String.Empty
            m_CurrentMachine.sCurrMill = String.Empty
            m_CurrentMachine.sCurrMilling = String.Empty
            m_CurrentMachine.sCurrWaterJet = String.Empty
            m_CurrentMachine.sCurrWaterJetting = String.Empty
            CurrCupWheelTxBl.Visibility = Windows.Visibility.Visible
            CurrCupWheelCmBx.Visibility = Windows.Visibility.Visible
         Case 4
            CreateToolList(MCH_TF.WATERJET, m_WaterJetList)
            m_WaterJetList.Add(NO_TOOL)
            If m_CurrentMachine.sCurrWaterJet = String.Empty Then
               CurrWJetCmBx.SelectedItem = NO_TOOL
            Else
               CurrWJetCmBx.SelectedItem = m_CurrentMachine.sCurrWaterJet
            End If
            m_CurrentMachine.sCurrDrill = String.Empty
            m_CurrentMachine.sCurrDrilling = String.Empty
            m_CurrentMachine.sCurrMill = String.Empty
            m_CurrentMachine.sCurrMilling = String.Empty
            m_CurrentMachine.sCurrMillNoTip = String.Empty
            m_CurrentMachine.sCurrPocketing = String.Empty
            CurrWJetTxBl.Visibility = Windows.Visibility.Visible
            CurrWJetCmBx.Visibility = Windows.Visibility.Visible
      End Select
      ' aggionro l'elenco delle lavoarzioni
      RefreschMachining()

   End Sub

#Region "Selection: SAW, DRILL, MILL, CUPWHEEL, WATERJET"
   ' -- SAW --
   Private Sub CurrSawCmBx_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles CurrSawCmBx.SelectionChanged
      If IsNothing(CurrSawCmBx.SelectedItem) Then Return
      ' Assegno
      m_CurrentMachine.sCurrSaw = CurrSawCmBx.SelectedItem.ToString()
      ' Se nuova lama incompatibile con lavorazione di taglio corrente, resetto quest'ultima
      Dim sMchTuuid As String = String.Empty
      Dim sMchTool As String = String.Empty
      If Not EgtMdbSetCurrMachining(m_CurrentMachine.sCurrSawing) Or
         Not EgtMdbGetCurrMachiningParam(MCH_MP.TUUID, sMchTuuid) Or
         Not EgtTdbGetToolFromUUID(sMchTuuid, sMchTool) Or
         String.Compare(sMchTool, m_CurrentMachine.sCurrSaw, True) <> 0 Then
         m_CurrentMachine.sCurrSawing = String.Empty
      End If
      ' Aggiorno utensili per lavoro in corso
      m_MainWindow.m_WorkInProgressPageUC.UpdateTools()
      ' aggiorno la lista delle lavorazioni
      RefreschMachining()
   End Sub

   ' -- DRILL --
   Private Sub CurrDrillCmBx_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles CurrDrillCmBx.SelectionChanged
      If IsNothing(CurrDrillCmBx.SelectedItem) Then Return
      ' Rimuovo foretto
      If CurrDrillCmBx.SelectedItem.ToString() = NO_TOOL Then
         m_CurrentMachine.sCurrDrill = String.Empty
         m_CurrentMachine.sCurrDrilling = String.Empty
         ' Assegno foretto
      Else
         m_CurrentMachine.sCurrDrill = CurrDrillCmBx.SelectedItem.ToString()
         ' Reset fresa, waterjet e relative lavorazioni
         If m_CurrentMachine.MountedToolConfig = CurrentMachine.MountedToolConfigs.SAWANDAUXTOOL Then
            m_CurrentMachine.sCurrMill = String.Empty
            m_CurrentMachine.sCurrMilling = String.Empty
            m_CurrentMachine.sCurrMillNoTip = String.Empty
            m_CurrentMachine.sCurrPocketing = String.Empty
            m_CurrentMachine.sCurrWaterJet = String.Empty
            m_CurrentMachine.sCurrWaterJetting = String.Empty
         End If
         ' Se nuovo foretto incompatibile con foratura corrente, resetto quest'ultima
         Dim sMchTuuid As String = String.Empty
         Dim sMchTool As String = String.Empty
         If Not EgtMdbSetCurrMachining(m_CurrentMachine.sCurrDrilling) Or
            Not EgtMdbGetCurrMachiningParam(MCH_MP.TUUID, sMchTuuid) Or
            Not EgtTdbGetToolFromUUID(sMchTuuid, sMchTool) Or
            String.Compare(sMchTool, m_CurrentMachine.sCurrDrill, True) <> 0 Then
            m_CurrentMachine.sCurrDrilling = String.Empty
         End If
      End If
      ' Aggiorno utensili per lavoro in corso
      m_MainWindow.m_WorkInProgressPageUC.UpdateTools()
      ' aggiorno la lista delle lavorazioni
      RefreschMachining()
   End Sub

   ' -- MILL --
   Private Sub CurrMillCmBx_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles CurrMillCmBx.SelectionChanged
      If IsNothing(CurrMillCmBx.SelectedItem) Then Return
      ' Rimuovo fresa
      If CurrMillCmBx.SelectedItem.ToString() = NO_TOOL Then
         m_CurrentMachine.sCurrMill = String.Empty
         m_CurrentMachine.sCurrMilling = String.Empty
         ' Assegno fresa
      Else
         m_CurrentMachine.sCurrMill = CurrMillCmBx.SelectedItem.ToString()
         ' Reset foretto, waterjet e relative lavorazioni
         If m_CurrentMachine.MountedToolConfig = CurrentMachine.MountedToolConfigs.SAWANDAUXTOOL Then
            m_CurrentMachine.sCurrDrill = String.Empty
            m_CurrentMachine.sCurrDrilling = String.Empty
            m_CurrentMachine.sCurrMillNoTip = String.Empty
            m_CurrentMachine.sCurrPocketing = String.Empty
            m_CurrentMachine.sCurrWaterJet = String.Empty
            m_CurrentMachine.sCurrWaterJetting = String.Empty
         End If
         ' Se nuova fresa incompatibile con fresatura corrente, resetto quest'ultima
         Dim sMchTuuid As String = String.Empty
         Dim sMchTool As String = String.Empty
         If Not EgtMdbSetCurrMachining(m_CurrentMachine.sCurrMilling) Or
            Not EgtMdbGetCurrMachiningParam(MCH_MP.TUUID, sMchTuuid) Or
            Not EgtTdbGetToolFromUUID(sMchTuuid, sMchTool) Or
            String.Compare(sMchTool, m_CurrentMachine.sCurrMill, True) <> 0 Then
            m_CurrentMachine.sCurrMilling = String.Empty
         End If
      End If
      ' Aggiorno utensili per lavoro in corso
      m_MainWindow.m_WorkInProgressPageUC.UpdateTools()
      ' aggiorno la lista delle lavorazioni
      RefreschMachining()
   End Sub

   ' -- CUPWHEEL --
   Private Sub CurrCupWheelCmBx_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles CurrCupWheelCmBx.SelectionChanged
      If IsNothing(CurrCupWheelCmBx.SelectedItem) Then Return
      ' Rimuovo fresa
      If CurrCupWheelCmBx.SelectedItem.ToString() = NO_TOOL Then
         m_CurrentMachine.sCurrMillNoTip = String.Empty
         m_CurrentMachine.sCurrPocketing = String.Empty
         ' Assegno fresa
      Else
         m_CurrentMachine.sCurrMillNoTip = CurrCupWheelCmBx.SelectedItem.ToString()
         ' Reset foretto, waterjet e relative lavorazioni
         If m_CurrentMachine.MountedToolConfig = CurrentMachine.MountedToolConfigs.SAWANDAUXTOOL Then
            m_CurrentMachine.sCurrDrill = String.Empty
            m_CurrentMachine.sCurrDrilling = String.Empty
            m_CurrentMachine.sCurrMill = String.Empty
            m_CurrentMachine.sCurrMilling = String.Empty
            m_CurrentMachine.sCurrWaterJet = String.Empty
            m_CurrentMachine.sCurrWaterJetting = String.Empty
         End If
         ' Se nuova fresa incompatibile con fresatura corrente, resetto quest'ultima
         Dim sMchTuuid As String = String.Empty
         Dim sMchTool As String = String.Empty
         If Not EgtMdbSetCurrMachining(m_CurrentMachine.sCurrPocketing) Or
            Not EgtMdbGetCurrMachiningParam(MCH_MP.TUUID, sMchTuuid) Or
            Not EgtTdbGetToolFromUUID(sMchTuuid, sMchTool) Or
            String.Compare(sMchTool, m_CurrentMachine.sCurrMillNoTip, True) <> 0 Then
            m_CurrentMachine.sCurrPocketing = String.Empty
         End If
      End If
      ' Aggiorno utensili per lavoro in corso
      m_MainWindow.m_WorkInProgressPageUC.UpdateTools()
      ' aggiorno la lista delle lavorazioni
      RefreschMachining()
   End Sub

   ' -- WATERJET --
   Private Sub CurrWJetCmBx_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles CurrWJetCmBx.SelectionChanged
      If IsNothing(CurrWJetCmBx.SelectedItem) Then Return
      ' Rimuovo Waterjet
      If CurrWJetCmBx.SelectedItem.ToString() = NO_TOOL Then
         m_CurrentMachine.sCurrWaterJet = String.Empty
         m_CurrentMachine.sCurrWaterJetting = String.Empty
         ' Assegno Waterjet
      Else
         m_CurrentMachine.sCurrWaterJet = CurrWJetCmBx.SelectedItem.ToString()
         ' Reset foretto, fresa e relative lavorazioni
         If m_CurrentMachine.MountedToolConfig = CurrentMachine.MountedToolConfigs.SAWANDAUXTOOL Then
            m_CurrentMachine.sCurrDrill = String.Empty
            m_CurrentMachine.sCurrDrilling = String.Empty
            m_CurrentMachine.sCurrMill = String.Empty
            m_CurrentMachine.sCurrMilling = String.Empty
         End If
         ' Se nuova Waterjet incompatibile con Waterjet corrente, resetto quest'ultima
         Dim sMchTuuid As String = String.Empty
         Dim sMchTool As String = String.Empty
         If Not EgtMdbSetCurrMachining(m_CurrentMachine.sCurrWaterJetting) Or
            Not EgtMdbGetCurrMachiningParam(MCH_MP.TUUID, sMchTuuid) Or
            Not EgtTdbGetToolFromUUID(sMchTuuid, sMchTool) Or
            String.Compare(sMchTool, m_CurrentMachine.sCurrWaterJet, True) <> 0 Then
            m_CurrentMachine.sCurrWaterJetting = String.Empty
         End If
      End If
      ' Aggiorno utensili per lavoro in corso
      m_MainWindow.m_WorkInProgressPageUC.UpdateTools()
      ' aggiorno la lista delle lavorazioni
      RefreschMachining()
   End Sub

#End Region    'Selection: SAW, DRILL, MILL, CUPWHEEL, WATERJET

   Public Overloads Sub CreateToolList(ToolType As Integer, ToolList As ObservableCollection(Of String))
      ToolList.Clear()
      Dim ToolName As String = String.Empty
      Dim nType As Integer = MCH_TY.NONE
      Dim bFound As Boolean = EgtTdbGetFirstTool(ToolType, ToolName, nType)
      While bFound
         ' Accetto utensili che non siano da sotto
         If String.Compare(ToolName, m_CurrentMachine.sCurrDripSaw, True) <> 0 AndAlso
            String.Compare(ToolName, m_CurrentMachine.sCurrDripDrill, True) <> 0 Then
            ToolList.Add(ToolName)
         End If
         bFound = EgtTdbGetNextTool(ToolType, ToolName, nType)
      End While
   End Sub

   ' definisce l'elenco degli utensili in funzione della famiglia e del tipo (usata per distingure i diversi tipi di frese)
   Public Overloads Sub CreateToolList(ToolFamily As Integer, ToolType As Integer, ToolList As ObservableCollection(Of String))
      ToolList.Clear()
      Dim ToolName As String = String.Empty
      Dim nType As Integer = ToolType
      Dim bFound As Boolean = EgtTdbGetFirstTool(ToolType, ToolName, nType)
      While bFound
         ' Accetto utensili che non siano da sotto
         If String.Compare(ToolName, m_CurrentMachine.sCurrDripSaw, True) <> 0 AndAlso
            String.Compare(ToolName, m_CurrentMachine.sCurrDripDrill, True) <> 0 AndAlso
            nType = ToolType Then
            ToolList.Add(ToolName)
         End If
         bFound = EgtTdbGetNextTool(ToolType, ToolName, nType)
      End While

   End Sub

   Private Sub SetUpBtn_Click(sender As Object, e As RoutedEventArgs) Handles SetUpBtn.Click
      m_MainWindow.m_MachinePageUC.MachinePageGrid.Children.Remove(Me)
      m_SetUpPage = New SetUpPage
      m_MainWindow.m_MachinePageUC.MachinePageGrid.Children.Add(m_SetUpPage)
   End Sub

   Private Sub HolesOffsetTxBx_EgtClosed(sender As Object, e As EventArgs) Handles HolesOffsetTxBx.EgtClosed
      Dim dVal As Double = 0
      StringToLen(HolesOffsetTxBx.Text, dVal)
      WritePrivateProfileString(S_MACH_NEST, K_MACH_HOLES_OFFSET, DoubleToString(dVal, 2), m_MainWindow.GetMachIniFile())
      EgtMdbSetGeneralParam(MCH_GP.EXTRARONDRIREG, dVal)
      EgtMdbSave()
   End Sub

   Private Sub HolesOverlapTxBx_EgtClosed(sender As Object, e As EventArgs) Handles HolesOverlapTxBx.EgtClosed
      Dim dVal As Double = 0
      StringToLen(HolesOverlapTxBx.Text, dVal)
      WritePrivateProfileString(S_MACH_NEST, K_MACH_HOLES_OVERLAP, DoubleToString(dVal, 2), m_MainWindow.GetMachIniFile())
   End Sub

   Private Sub HolesToleranceTxBx_EgtClosed(sender As Object, e As EventArgs) Handles HolesToleranceTxBx.EgtClosed
      Dim dVal As Double = 0
      StringToLen(HolesToleranceTxBx.Text, dVal)
      WritePrivateProfileString(S_MACH_NEST, K_MACH_HOLES_DIAMTOLER, DoubleToString(dVal, 2), m_MainWindow.GetMachIniFile())
      EgtMdbSetGeneralParam(MCH_GP.HOLEDIAMTOLER, dVal)
      EgtMdbSave()
   End Sub

   Private Sub OneHoleInCornerChBx_Click(sender As Object, e As RoutedEventArgs) Handles OneHoleInCornerChBx.Click
      If OneHoleInCornerChBx.IsChecked() Then
         WritePrivateProfileString(S_MACH_NEST, K_MACH_ONEHOLE_INTCORNER, "1", m_MainWindow.GetMachIniFile())
      Else
         WritePrivateProfileString(S_MACH_NEST, K_MACH_ONEHOLE_INTCORNER, "0", m_MainWindow.GetMachIniFile())
      End If
   End Sub

   Private Sub CutExtraLenTxBx_EgtClosed(sender As Object, e As EventArgs) Handles CutExtraLenTxBx.EgtClosed
      Dim dVal As Double = 0
      StringToLen(CutExtraLenTxBx.Text, dVal)
      WritePrivateProfileString(S_MACH_NEST, K_MACH_SAFE_LEN_CUT, DoubleToString(dVal, 2), m_MainWindow.GetMachIniFile())
      EgtMdbSetGeneralParam(MCH_GP.EXTRALONCUTREG, dVal)
      EgtMdbSave()
   End Sub

   Private Sub AngleCutExtraLenTxBx_EgtClosed(sender As Object, e As EventArgs) Handles AngleCutExtraLenTxBx.EgtClosed
      Dim dVal As Double = 0
      StringToLen(AngleCutExtraLenTxBx.Text, dVal)
      WritePrivateProfileString(S_MACH_NEST, K_MACH_SAFE_LEN_INTCORNER, DoubleToString(dVal, 2), m_MainWindow.GetMachIniFile())
   End Sub

   Private Sub SafeZTxBx_EgtClosed(sender As Object, e As EventArgs) Handles SafeZTxBx.EgtClosed
      Dim dSafeZ As Double = 0
      StringToLen(SafeZTxBx.Text, dSafeZ)
      EgtMdbSetGeneralParam(MCH_GP.SAFEZ, dSafeZ)
      EgtMdbSave()
   End Sub

   Private Sub ExtArcMinRadTxBx_EgtClosed(sender As Object, e As EventArgs) Handles ExtArcMinRadTxBx.EgtClosed
      Dim dVal As Double = 0
      StringToLen(ExtArcMinRadTxBx.Text, dVal)
      WritePrivateProfileString(S_MACH_NEST, K_MACH_EXTARCMINRAD, DoubleToString(dVal, 2), m_MainWindow.GetMachIniFile())
      EgtMdbSetGeneralParam(MCH_GP.EXTSAWARCMINRAD, dVal)
      EgtMdbSave()
   End Sub

   Private Sub IntArcMaxSideAngTxBx_EgtClosed(sender As Object, e As EventArgs) Handles IntArcMaxSideAngTxBx.EgtClosed
      Dim dVal As Double = 0
      StringToDouble(IntArcMaxSideAngTxBx.Text, dVal)
      WritePrivateProfileString(S_MACH_NEST, K_MACH_INTARCMAXSIDEANG, DoubleToString(dVal, 2), m_MainWindow.GetMachIniFile())
      EgtMdbSetGeneralParam(MCH_GP.INTSAWARCMAXSIDEANG, dVal)
      EgtMdbSave()
   End Sub

   Private Sub PreCutExitChBx_Click(sender As Object, e As RoutedEventArgs) Handles PreCutExitChBx.Click
      If PreCutExitChBx.IsChecked Then
         WritePrivateProfileString(S_MACH_NEST, K_MACH_PRECUTEXIT, "1", m_MainWindow.GetMachIniFile())
      Else
         WritePrivateProfileString(S_MACH_NEST, K_MACH_PRECUTEXIT, "0", m_MainWindow.GetMachIniFile())
      End If
   End Sub

   Private Sub CompleteCutsChBx_Click(sender As Object, e As RoutedEventArgs) Handles CompleteCutsChBx.Click
      Dim NestPage As NestPageUC = m_MainWindow.m_CadCutPageUC.m_NestPage
      If CompleteCutsChBx.IsChecked() Then
         ' Se pezzi in interferenza
         If Not NestPage.VerifyPartsNesting(False) Then
            ' Ci sono interferenze, alcuni pezzi saranno parcheggiati. Vuoi continuare ?
            Dim Dlg As EgtMsgBox
            If m_MainWindow.IsSiemensPc Then
               Dlg = New EgtMsgBox(m_MainWindow, Me.ActualWidth / 15 * 5.5, EgtMsgBox.WidthType.PIXEL, "", EgtMsg(91105), EgtMsgBox.Buttons.OK_CANCEL, EgtMsgBox.Icons.NULL, 1, 1)
            Else
               Dlg = New EgtMsgBox(m_MainWindow, "", EgtMsg(91105), EgtMsgBox.Buttons.OK_CANCEL, EgtMsgBox.Icons.NULL, 1, 1)
            End If
            If Dlg.m_nPressedBtn = 1 Then        ' Ok
               NestPage.StoreCollisionParts(False)
               WritePrivateProfileString(S_MACH_NEST, K_MACH_REDUCEDCUT, "0", m_MainWindow.GetMachIniFile())
            End If
         Else
            WritePrivateProfileString(S_MACH_NEST, K_MACH_REDUCEDCUT, "0", m_MainWindow.GetMachIniFile())
         End If
      Else
         WritePrivateProfileString(S_MACH_NEST, K_MACH_REDUCEDCUT, "1", m_MainWindow.GetMachIniFile())
      End If
      AdjustGhigliottinaTextOnAutomaticOrCompleteCuts()
   End Sub

   Private Sub CornerCutsChBx_Click(sender As Object, e As RoutedEventArgs) Handles CornerCutsChBx.Click
      If CornerCutsChBx.IsChecked() Then
         WritePrivateProfileString(S_MACH_NEST, K_MACH_MILLING_ON_CORNERS, "1", m_MainWindow.GetMachIniFile())
      Else
         WritePrivateProfileString(S_MACH_NEST, K_MACH_MILLING_ON_CORNERS, "0", m_MainWindow.GetMachIniFile())
      End If
   End Sub

   Private Sub ShortTxBx_EgtClosed(sender As Object, e As EventArgs) Handles ShortTxBx.EgtClosed
      Dim dVal As Double = 0
      StringToLen(ShortTxBx.Text, dVal)
      WritePrivateProfileString(S_MACH_NEST, K_MACH_MILLING_SHORTENING, DoubleToString(dVal, 2), m_MainWindow.GetMachIniFile())
   End Sub

   Private Sub InternalCutsChBx_Click(sender As Object, e As RoutedEventArgs) Handles InternalCutsChBx.Click
      If InternalCutsChBx.IsChecked() Then
         WritePrivateProfileString(S_MACH_NEST, K_MACH_MILLING_ON_SINKS, "1", m_MainWindow.GetMachIniFile())
      Else
         WritePrivateProfileString(S_MACH_NEST, K_MACH_MILLING_ON_SINKS, "0", m_MainWindow.GetMachIniFile())
      End If
   End Sub

   Private Sub WjIntCutsChBx_Click(sender As Object, e As RoutedEventArgs) Handles WjIntCutsChBx.Click
      If WjIntCutsChBx.IsChecked() Then
         WritePrivateProfileString(S_MACH_NEST, K_MACH_MILLING_ON_SINKS, "1", m_MainWindow.GetMachIniFile())
      Else
         WritePrivateProfileString(S_MACH_NEST, K_MACH_MILLING_ON_SINKS, "0", m_MainWindow.GetMachIniFile())
      End If
   End Sub

   Private Sub TmEnableChBx_Click(sender As Object, e As RoutedEventArgs) Handles TmEnableChBx.Click
      If TmEnableChBx.IsChecked() Then
         WritePrivateProfileString(S_MACH_NEST, K_MACH_ENGRAVING_WITHMILL, "1", m_MainWindow.GetMachIniFile())
      Else
         WritePrivateProfileString(S_MACH_NEST, K_MACH_ENGRAVING_WITHMILL, "0", m_MainWindow.GetMachIniFile())
      End If
   End Sub

   Private Sub TmDepthTxBx_EgtClosed(sender As Object, e As EventArgs) Handles TmDepthTxBx.EgtClosed
      Dim dVal As Double = 0
      StringToLen(TmDepthTxBx.Text, dVal)
      WritePrivateProfileString(S_MACH_NEST, K_MACH_ENGRAVING_DEPTH, DoubleToString(dVal, 2), m_MainWindow.GetMachIniFile())
   End Sub

   Private Sub TmWidthTxBx_EgtClosed(sender As Object, e As EventArgs) Handles TmWidthTxBx.EgtClosed
      Dim dVal As Double = 0
      StringToLen(TmWidthTxBx.Text, dVal)
      WritePrivateProfileString(S_MACH_NEST, K_MACH_ENGRAVING_WIDTH, DoubleToString(dVal, 2), m_MainWindow.GetMachIniFile())
   End Sub

   Private Sub FinalHomeChBx_Click(sender As Object, e As RoutedEventArgs) Handles FinalHomeChBx.Click
      If FinalHomeChBx.IsChecked() Then
         m_MainWindow.m_CurrentMachine.bDirectCutsFinalHome = True
      Else
         m_MainWindow.m_CurrentMachine.bDirectCutsFinalHome = False
      End If
   End Sub

   Private Sub AlignChBx_Click(sender As Object, e As RoutedEventArgs) Handles AlignChBx.Click
      If AlignChBx.IsChecked() Then
         WritePrivateProfileString(S_MACH_NEST, K_MACH_NEST_ALIGNED, "1", m_MainWindow.GetMachIniFile())
      Else
         WritePrivateProfileString(S_MACH_NEST, K_MACH_NEST_ALIGNED, "0", m_MainWindow.GetMachIniFile())
      End If
   End Sub

   Private Sub GligliottinaChBx_Click(sender As Object, e As RoutedEventArgs) Handles GhigliottinaChBx.Click
      If GhigliottinaChBx.IsChecked() Then
         WritePrivateProfileString(S_MACH_NEST, K_MACH_NEST_GHIGLIOTTINA, "1", m_MainWindow.GetMachIniFile())
      Else
         WritePrivateProfileString(S_MACH_NEST, K_MACH_NEST_GHIGLIOTTINA, "0", m_MainWindow.GetMachIniFile())
      End If
   End Sub

   Private Sub AutomaticChBx_Click(sender As Object, e As RoutedEventArgs) Handles AutomaticChBx.Click
      If AutomaticChBx.IsChecked() Then
         WritePrivateProfileString(S_NEST, K_AUTOMATICOPTIMIZE, "1", m_MainWindow.GetIniFile())
      Else
         WritePrivateProfileString(S_NEST, K_AUTOMATICOPTIMIZE, "0", m_MainWindow.GetIniFile())
      End If
      AdjustGhigliottinaTextOnAutomaticOrCompleteCuts()
   End Sub

   Private Sub AdjustGhigliottinaTextOnAutomaticOrCompleteCuts()
      If AutomaticChBx.IsChecked() And Not CompleteCutsChBx.IsChecked() Then
         GhigliottinaTxBl.Visibility = Visibility.Visible
         GhigliottinaChBx.Visibility = Visibility.Visible
      Else
         GhigliottinaTxBl.Visibility = Visibility.Collapsed
         GhigliottinaChBx.Visibility = Visibility.Collapsed
      End If
   End Sub

   Private Sub AdditionalTableTxBx_EgtClosed(sender As Object, e As EventArgs) Handles AdditionalTableTxBx.EgtClosed
      Dim dVal As Double = 0
      StringToLen(AdditionalTableTxBx.Text, dVal)
      m_MainWindow.m_CurrentMachine.dAdditionalTable = dVal
   End Sub

   Private Sub NewMatBtn_Click(sender As Object, e As RoutedEventArgs) Handles NewMatBtn.Click
      ' Mostro textbox per il nome
      MatNameTxBx.Text = String.Empty
      MatNameTxBx.Visibility = Windows.Visibility.Visible
      MaterialsLstBx.SetValue(Grid.RowSpanProperty, 1)
   End Sub

   Private Sub MatNameTxBx_EgtClosed(sender As Object, e As EventArgs) Handles MatNameTxBx.EgtClosed
      ' Verifico che il nome non sia vuoto
      If Not String.IsNullOrWhiteSpace(MatNameTxBx.Text) Then
         ' Verifico che il nome non sia già utilizzato
         Dim bNameExist As Boolean = False
         For Each Material As Material In m_CurrentMachine.Materials
            If Material.sName = MatNameTxBx.Text Then
               bNameExist = True
               Exit For
            End If
         Next
         If Not bNameExist Then
            m_CurrentMachine.AddMaterial(New Material(MatNameTxBx.Text, m_CurrentMachine.Materials))
         End If
      End If
      ' Nascondo textbox per il nome
      MaterialsLstBx.SetValue(Grid.RowSpanProperty, 2)
      MatNameTxBx.Visibility = Windows.Visibility.Hidden
   End Sub

   Private Sub RemoveMatBtn_Click(sender As Object, e As RoutedEventArgs) Handles RemoveMatBtn.Click
      Dim SelectedMat As Material = DirectCast(MaterialsLstBx.SelectedItem, Material)
      If Not IsNothing(SelectedMat) Then
         m_CurrentMachine.RemoveMaterial(SelectedMat)
      End If
   End Sub

   Private Sub BackImageBtn_Click(sender As Object, e As RoutedEventArgs) Handles BackImageBtn.Click
      ' Se macchina fotografica abilitata, faccio una foto
      If m_MainWindow.m_Camera.GetCameraLink() Then
         If m_MainWindow.m_Camera.CameraBackImage() Then
            m_MainWindow.m_CurrentProjectPageUC.SetInfoMessage(EgtMsg(90323))     'Fotografia di sfondo riuscita
         Else
            m_MainWindow.m_CurrentProjectPageUC.SetErrorMessage(EgtMsg(90313))    'Fotografia non riuscita
         End If
      End If
   End Sub

   Private Sub ThresholdTxBx_EgtClosed(sender As Object, e As EventArgs) Handles ThresholdTxBx.EgtClosed
      ' Recupero il valore
      Dim nVal As Integer = 0
      StringToInt(ThresholdTxBx.Text, nVal)
      ' Lo imposto
      m_MainWindow.m_Camera.Threshold = nVal
      ' Lo recupero, potrebbe essere stato aggiustato
      ThresholdTxBx.Text = m_MainWindow.m_Camera.Threshold.ToString()
   End Sub

   Private Sub ToleranceTxBx_EgtClosed(sender As Object, e As EventArgs) Handles ToleranceTxBx.EgtClosed
      ' Recupero il valore
      Dim dVal As Double = 0
      StringToLen(ToleranceTxBx.Text, dVal)
      ' Lo imposto
      m_MainWindow.m_Camera.Tolerance = dVal
      ' Lo recupero, potrebbe essere stato aggiustato
      ToleranceTxBx.Text = LenToString(m_MainWindow.m_Camera.Tolerance, 3)
   End Sub

   Private Sub SideAngCutProbeChBx_Click(sender As Object, e As RoutedEventArgs) Handles SideAngCutProbeChBx.Click
      If SideAngCutProbeChBx.IsChecked() Then
         WritePrivateProfileString(S_MACH_NEST, K_MACH_SACPROBE, "1", m_MainWindow.GetMachIniFile())
      Else
         WritePrivateProfileString(S_MACH_NEST, K_MACH_SACPROBE, "0", m_MainWindow.GetMachIniFile())
      End If
   End Sub

   Private Sub UseLaserOriginChBx_Click() Handles UseLaserOriginChBx.Click
      If UseLaserOriginChBx.IsChecked() Then
         WritePrivateProfileString(S_TABLE, K_USELASERORIGIN, "1", m_MainWindow.GetMachIniFile())
      Else
         WritePrivateProfileString(S_TABLE, K_USELASERORIGIN, "0", m_MainWindow.GetMachIniFile())
      End If
   End Sub

   Private Sub WashingChBx_Click(sender As Object, e As RoutedEventArgs) Handles WashingChBx.Click
      If WashingChBx.IsChecked() Then
         WritePrivateProfileString(S_MACH_NEST, K_MACH_WASHING, "1", m_MainWindow.GetMachIniFile())
      Else
         WritePrivateProfileString(S_MACH_NEST, K_MACH_WASHING, "0", m_MainWindow.GetMachIniFile())
      End If
   End Sub

   Private Sub CfrLenTxBx_Click(sender As Object, e As RoutedEventArgs) Handles CfrLenTxBx.EgtClosed
      ' Recupero il valore
      Dim dVal As Double = 0
      StringToLen(CfrLenTxBx.Text, dVal)
      ' Lo imposto
      m_CurrentMachine.dFsevLength = dVal
   End Sub

   Private Sub CfrPercTxBx_Click(sender As Object, e As RoutedEventArgs) Handles CfrPercTxBx.EgtClosed
      ' Recupero il valore
      Dim dVal As Double = 0
      StringToDouble(CfrPercTxBx.Text, dVal)
      ' Lo imposto
      m_CurrentMachine.dFsevPerc = dVal
   End Sub

   Private Sub FramePauseChBx_Click(sender As Object, e As RoutedEventArgs) Handles FramePauseChBx.Click
      If FramePauseChBx.IsChecked() Then
         WritePrivateProfileString(S_MACH_FRAME, K_MACH_PAUSE, "1", m_MainWindow.GetMachIniFile())
      Else
         WritePrivateProfileString(S_MACH_FRAME, K_MACH_PAUSE, "0", m_MainWindow.GetMachIniFile())
      End If
   End Sub

   Private Sub SawProbingBtn_Click(sender As Object, e As RoutedEventArgs) Handles SawProbingBtn.Click
      ' imposto modo automatico
      Select Case m_MainWindow.m_CNCommunication.m_nNCType
         Case 1, 2
            ' in attesa di verifica 
         Case 3
            Dim nResult As Short = m_CN.DGeneralFunctions_WriteCncMode(0)
            EgtOutLog("Impostata modalità automatica: esito " & nResult.ToString)
      End Select
      ' Recupero file LUA
      EgtLuaExecFile(m_MainWindow.m_CurrentMachine.sMachDir() & "\DirectCmd\SawProbing.lua")
      ' Recupero utensile da tastare
      Dim ToolForProbing As ToolPos = ChooseToolForProbing()
      If IsNothing(ToolForProbing) OrElse String.IsNullOrWhiteSpace(ToolForProbing.m_ToolName) Then Return
      If Not EgtTdbSetCurrTool(ToolForProbing.m_ToolName) Then Return
      ' Imposto parametri
      Dim dToolDiam As Double = 0
      Dim dToolThick As Double = 0
      Dim dToolLen As Double = 0
      Dim sToolParam As String = String.Empty
      EgtTdbGetCurrToolParam(MCH_TP.HEAD, sToolParam)
      EgtLuaSetGlobStringVar("CMD.HEAD", sToolParam)
      EgtLuaSetGlobStringVar("CMD.TCPOS", ToolForProbing.m_ToolPos)
      EgtLuaSetGlobBoolVar("CMD.ISSAW", ToolForProbing.m_IsSaw)
      EgtTdbGetCurrToolParam(MCH_TP.DIAM, dToolDiam)
      EgtLuaSetGlobNumVar("CMD.DIAM", dToolDiam * 1000)
      EgtTdbGetCurrToolParam(MCH_TP.THICK, dToolThick)
      EgtLuaSetGlobNumVar("CMD.THICK", dToolThick * 1000)
      EgtTdbGetCurrToolParam(MCH_TP.LEN, dToolLen)
      EgtLuaSetGlobNumVar("CMD.LENGTH", dToolLen * 1000)
      EgtLuaSetGlobBoolVar("CMD.INCHES", m_MainWindow.m_CNCommunication.GetMachineInInches())
      EgtLuaCallFunction("CMD.CmdString")
      ' Leggo variabili
      Dim CmdString As String = String.Empty
      EgtLuaGetGlobStringVar("CMD.CMDSTRING", CmdString)
      Dim nErr As Integer = 0
      EgtLuaGetGlobIntVar("CMD.ERR", nErr)
      ' Reset lua
      EgtLuaResetGlobVar("CMD")
      ' Verifico condizioni di errore
      If nErr <> 0 Or String.IsNullOrWhiteSpace(CmdString) Then
         ' Errore in tastatura lama
         Dim MsgBoxError As New EgtMsgBox(m_MainWindow, "", EgtMsg(MSG_DIRECTCUTPAGEUC + 44), EgtMsgBox.Buttons.OK, EgtMsgBox.Icons.NULL)
         EgtOutLog("ToolProbing Command error")
         Return
      End If
      ' Modifico stringa per inserire i newline
      CmdString = CmdString.Replace("<br/>", Environment.NewLine)
      ' Creo file...
      Dim FilePath As String = m_MainWindow.GetCncDir() & "\SawProbing" & m_MainWindow.m_CurrentMachine.sIsoFileExt
      ' ...e ci scrivo
      Dim Writer As New IO.StreamWriter(FilePath, False)
      Writer.Write(CmdString)
      Writer.Close()
      ' Verifico se sono connesso alla macchina prima di continuare
      If Not m_MainWindow.m_bNCLink Then
         EgtOutLog("ToolProbing NcLink error")
         Return
      End If
      ' Leggo nome variabile tastatura eseguita
      Dim ProbingStateNameVar As String = String.Empty
      GetPrivateProfileString(S_MACH_PROBING, K_PROBINGSTATEVAR, "", ProbingStateNameVar, m_MainWindow.GetMachIniFile())
      ' Eseguo reset variabile tastatura eseguita
      m_MainWindow.m_CNCommunication.m_CN.DVariables_WriteVariables2(ProbingStateNameVar, "0")
      System.Threading.Thread.Sleep(300)
      ' Mando file al CN
      If Not m_MainWindow.m_CNCommunication.SendProgram(FilePath, 900) Then
         ' Errore in tastatura lama
         Dim MsgBoxError As New EgtMsgBox(m_MainWindow, "", EgtMsg(MSG_DIRECTCUTPAGEUC + 44), EgtMsgBox.Buttons.OK, EgtMsgBox.Icons.NULL)
         EgtOutLog("ToolProbing Send error")
         Return
      End If
      m_MainWindow.m_CurrentProjectPageUC.ClearMessage()
      ' Aspetto e lo avvio
      System.Threading.Thread.Sleep(300)
      m_MainWindow.m_CNCommunication.m_CN.DGeneralFunctions_CycleStart()
      ' Creo MsgBox di attesa
      Dim MsgBoxStateInfo As New EgtMsgBox(m_MainWindow, EgtMsg(MSG_DIRECTCUTPAGEUC + 41), EgtMsg(MSG_DIRECTCUTPAGEUC + 42), True, EgtMsgBox.Buttons.CANCEL, EgtMsgBox.Icons.NULL)
      m_MainWindow.m_CNCommunication.m_CN.n_DReadELS_handle = 0
      ' Definisco flag tastatura
      Dim bProbingOk As Boolean = False
      For I As Integer = 0 To 120
         ' Devo rileggere la variabile ad ogni ciclo
         m_MainWindow.m_CNCommunication.m_CN.ReadEls_Add_Parameter(ProbingStateNameVar, 3)
         System.Threading.Thread.Sleep(100)
         If m_MainWindow.m_CNCommunication.m_CN.n_DReadELS_handle = 3 Then
            Dim L108Val As Integer = CInt(m_MainWindow.m_CNCommunication.m_CN.d_DReadELS_value)
            Select Case L108Val
               Case 0
                  ' Non faccio alcunchè perchè sta tastando
               Case 1
                  ' Tastatura completata
                  bProbingOk = True
                  Exit For
               Case 2
                  ' Errore
                  bProbingOk = False
                  Exit For
            End Select
         End If
         System.Threading.Thread.Sleep(900)
         ' Incremento progressbar
         MsgBoxStateInfo.LoadingPrBr_Value += 100 / 120
         ' Costringo ad aggiornare UI
         UpdateUI()
         ' Verifico se interrotto dall'utente
         If MsgBoxStateInfo.m_nPressedBtn = 0 Then
            MsgBoxStateInfo.Close()
            UpdateUI()
            System.Threading.Thread.Sleep(100)
            EgtOutLog("ToolProbing canceled by user")
            ' Tastatura interrotta dall'utente
            Dim MsgBoxError As New EgtMsgBox(m_MainWindow, "", EgtMsg(MSG_DIRECTCUTPAGEUC + 46), EgtMsgBox.Buttons.OK, EgtMsgBox.Icons.NULL)
            Return
         End If
      Next
      ' Se tastatura riuscita
      If bProbingOk Then
         ' Leggo valore misurato (diametro per lama, lunghezza per altri utensili)
         Dim bRead As Boolean = False
         Dim SawDiameterNameVar As String = String.Empty
         GetPrivateProfileString(S_MACH_PROBING, K_SAWDIAMETER, "", SawDiameterNameVar, m_MainWindow.GetMachIniFile())
         m_MainWindow.m_CNCommunication.m_CN.n_DReadELS_handle = 0
         For I As Integer = 0 To 20
            ' Devo rileggere la variabile ad ogni ciclo
            m_MainWindow.m_CNCommunication.m_CN.ReadEls_Add_Parameter(SawDiameterNameVar, 3)
            System.Threading.Thread.Sleep(100)
            If m_MainWindow.m_CNCommunication.m_CN.n_DReadELS_handle = 3 Then
               bRead = True
               Dim dVal As Double = m_MainWindow.m_CNCommunication.m_CN.d_DReadELS_value
               dVal = dVal / 1000
               MsgBoxStateInfo.LoadingPrBr_Value = 100
               ' Tastatura conclusa con successo
               Dim sOut As String = EgtMsg(MSG_DIRECTCUTPAGEUC + 43) & " : " & DoubleToString(dVal, 1)
               MsgBoxStateInfo.Text = sOut
               m_MainWindow.m_CurrentProjectPageUC.SetInfoMessage(sOut)
               EgtOutLog("ToolVal=" & dVal.ToString())
               ' Costringo ad aggiornare UI
               UpdateUI()
               ' Trasformo misura rilevata in mm
               dVal *= If(m_MainWindow.m_CNCommunication.GetMachineInInches(), ONEINCH, ONEMM)
               ' Imposto valore misurato
               If dVal > EPS_SMALL Then
                  ' Recupero utensile dal Db utensili
                  EgtTdbSetCurrTool(ToolForProbing.m_ToolName)
                  ' Se lama è il diametro, altrimenti la lunghezza
                  If ToolForProbing.m_IsSaw Then
                     EgtTdbSetCurrToolParam(MCH_TP.DIAM, dVal)
                     EgtTdbSetCurrToolParam(MCH_TP.TOTDIAM, dVal)
                  Else
                     EgtTdbSetCurrToolParam(MCH_TP.LEN, dVal)
                     EgtTdbSetCurrToolParam(MCH_TP.TOTLEN, dVal)
                  End If
                  EgtTdbSaveCurrTool()
                  EgtTdbSave()
               End If
               ' Chiudo msgbox
               System.Threading.Thread.Sleep(3000)
               MsgBoxStateInfo.Close()
               Exit For
            End If
            System.Threading.Thread.Sleep(100)
         Next
         If Not bRead Then bProbingOk = False
      End If
      ' Se tastatura non riuscita
      If Not bProbingOk Then
         MsgBoxStateInfo.Close()
         UpdateUI()
         System.Threading.Thread.Sleep(100)
         EgtOutLog("ToolProbing error")
         ' Errore in tastatura lama
         Dim MsgBoxError As New EgtMsgBox(m_MainWindow, "", EgtMsg(MSG_DIRECTCUTPAGEUC + 44), EgtMsgBox.Buttons.OK, EgtMsgBox.Icons.NULL)
      End If
   End Sub

   Private Function ChooseToolForProbing() As ToolPos
      Select Case m_MainWindow.m_CurrentMachine.MountedToolConfig
         Case CurrentMachine.MountedToolConfigs.SAW
            Return New ToolPos(m_MainWindow.m_CurrentMachine.sCurrSaw, "T100", True)
         Case CurrentMachine.MountedToolConfigs.SAWANDAUXTOOL, CurrentMachine.MountedToolConfigs.MANUALTOOLCHANGER, CurrentMachine.MountedToolConfigs.TOOLCHANGER
            Dim ChooseTool As New ChooseToolWD(m_MainWindow)
            If ChooseTool.ShowDialog Then
               Return ChooseTool.GetSelectedTool
            Else
               Return Nothing
            End If
         Case Else
            Return Nothing
      End Select
   End Function

   Friend Sub NcError()
      If m_CN.sz_NC_error_messages.Count > 0 Then
         'NCErrorMessages.Text = m_CN.sz_NC_error_messages(0)
         If m_CN.bIsErrorMessage Then
            m_MainWindow.m_MachineStatusUC.MachineStatusGrid.Background = Application.Current.FindResource("OmagCut_Red")
         Else
            m_MainWindow.m_MachineStatusUC.MachineStatusGrid.Background = Application.Current.FindResource("OmagCut_DarkGray")
         End If
      Else
         'NCErrorMessages.Text = ""
         Dim BackColor As SolidColorBrush = m_MainWindow.m_MachineStatusUC.MachineStatusGrid.Background
         If Colors.Red.Equals(BackColor.Color) Then
            m_MainWindow.m_MachineStatusUC.MachineStatusGrid.Background = Application.Current.FindResource("OmagCut_DarkGray")
         End If
      End If
   End Sub

   Friend Sub PlcError(ErrorMsg As String)
      '   m_MainWindow.m_MachineStatusUC.Background = Brushes.Red
      '   Dim sFilePath As String = m_MainWindow.GetMachinesRootDir() & "/PLCMessages/" & EgtMsg(MSG_MACHINEPAGEUC + 1)
      '   Try
      '      Dim sErrorText As String = File.ReadLines(sFilePath).Skip(m_CN.sz_PLC_error_messages).Take(1).First()
      '      sErrorText = sErrorText.Substring(sErrorText.IndexOf("$"))
      '      If sErrorText(0) = " " Then
      '         sErrorText = sErrorText.Substring(1)
      '      End If
      '      PLCErrorMessages.Text = sErrorText
      '   Catch ex As Exception
      '      MsgBox("Errore lettura errori PLC")
      '   End Try

   End Sub

End Class
