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

Class MainWindow

   ' Mutex per avere una sola istanza del programma in esecuzione
   Private m_objMutex As New Mutex

   ' Dichiarazione della classe di connessione al CN
   Friend m_CNCommunication As CNCommunication
   ' Variabile per presenza collegamento al CN
   Friend m_bNCLink As Boolean = False

   ' Dichiarazione della MachineStatusBar
   Friend m_MachineStatusUC As MachineStatusUC

   ' Coefficiente di scalatura della finestra rispetto a standard
   Friend m_dMWinScale As Double = 1

   ' Dichiarazione delle Page UserControl
   Friend m_WorkInProgressPageUC As WorkInProgressPageUC
   Friend m_CurrentProjectPageUC As CurrentProjectPageUC
   Friend m_DirectCutPageUC As DirectCutPageUC
   Friend m_CadCutPageUC As CadCutPageUC
   Friend m_OpenPage As OpenPageUC
   Friend m_PhotoPage As PhotoPageUC
   Friend m_RawPartPage As RawPartPageUC
   Friend m_DrawPageUC As DrawPageUC
   Friend m_ImportPageUC As ImportPageUC
   Friend m_SimulationPage As SimulationPageUC
   Friend m_FrameCutPageUC As FrameCutPageUC
   Friend m_MachinePageUC As MachinePageUC
   Friend m_OptionsPageUC As OptionsPageUC

   ' Dichiarazione variabili direttori
   Private m_sExeRoot As String = String.Empty
   Private m_sDataRoot As String = String.Empty
   Private m_sConfigDir As String = String.Empty
   Private m_sResourcesDir As String = String.Empty
   Private m_sTempDir As String = String.Empty
   Private m_sSaveDir As String = String.Empty
   Private m_sNamedSaveDir As String = String.Empty
   Private m_sCopyProjDir As String = String.Empty
   Private m_sCopyTemplateDir As String = String.Empty
   Private m_sCncDir As String = String.Empty
   Private m_sMachinesRoot As String = String.Empty
   Private m_sToolMakersDir As String = String.Empty
   Private m_sIniFile As String = String.Empty
   Private m_sMachIniFile As String = String.Empty
   Private m_sKitsFile As String = String.Empty
   Private m_sLogFile As String = String.Empty
   Private m_nDebug As Integer = 0
   Private m_sVersion As String = "1.1a1"

   'Dichiarazione variabile contenente la lingua corrente
   Friend m_CurrLanguage As Language
   'Dichiarazione lista delle lingue disponibili e lingua corrente
   Friend m_LanguagesList As New List(Of Language)

   ' Dichiarazione classe macchina
   Friend m_CurrentMachine As CurrentMachine
   ' Macchina corrente
   Private m_sCurrMachine As String = String.Empty

   ' Oggetto di gestione della macchina fotografica
   Friend m_Camera As New Camera

   ' Livello della licenza attiva associata alla chiave
   Private m_nKeyLevel As Integer = 0
   ' Opzioni abilitate dalla licenza attiva associata alla chiave
   Private m_nKeyOptions As UInteger = 0
   Friend Enum KEY_OPT As UInteger
      CUT_BASE = 2 ^ 0                    '       1 - Prodotto OmagCUT
      MAN_MANIP = 2 ^ 1                   '       2
      AUTO_MANIP = 2 ^ 2                  '       4
      MAN_PHOTO = 2 ^ 3                   '       8
      AUTO_PHOTO = 2 ^ 4                  '      16
      CSV_AUTO = 2 ^ 5                    '      32
      ENABLE_MILL = 2 ^ 6                 '      64
      PRODUCTION_LINE = 2 ^ 7             '     128
      OFFICE_BASE = 2 ^ 8                 '     256 - Prodotto OmagOFFICE
      VM_MULTI = 2 ^ 9                    '     512
      UNDER_CUT = 2 ^ 10                  '    1024
      CSV_SIMPLE = 2 ^ 11                 '    2048
      PHOTO_BASE = 2 ^ 12                 '    4096 - Prodotto OmagPHOTO
      TRF_IMPORT = 2 ^ 13                 '    8192
      MOVE_PARTS = 2 ^ 14                 '   16384
      IMPORT_SLABDXF = 2 ^ 15             '   32768
      CURVED_FRAME = 2 ^ 16               '   65536
      ENABLE_WJ = 2 ^ 17                  '  131072
      ENABLE_POLISHING = 2 ^ 18           '  262144
      OFFICE_TYPE = 2 ^ 19                '  524288
      REGISTRATION = 2 ^ 20               ' 1048576
      SIMPLESTATISTICS = 2 ^ 21           ' 2097152
   End Enum
   ' Opzione nesting automatico
   Private m_bAutoNest As Boolean = False

   ' Dichiarazione lista per ListBox della ImportPage
   Friend m_ImportItemList As New ObservableCollection(Of IconListBoxItem)
   Friend m_OpenItemList As New ObservableCollection(Of IconListBoxItem)
   Friend m_PhotoItemList As New ObservableCollection(Of IconListBoxItem)

   ' Riferimento alla pagina correntemente attiva
   Friend m_ActivePage As Pages
   Friend m_PrevActivePage As Pages    ' Funziona solo per tornare indietro da grezzo e foto !!

   ' Timer per aggiornamento interfaccia
   Private m_IdleTimer As New DispatcherTimer

   ' Timer per linea di produzione
   Private m_ProdLineTimer As New DispatcherTimer

   ' Variabile che indica il tipo di pc su cui gira il programma
   Private m_bIsSiemensPc As Boolean = False

   ' Variabile che indica il colore corrente di ColorToSIdeAng in OptionsPageUC
   Friend m_brCurrentColor As Brush

   Friend Enum Pages
      WorkInProgress
      DirectCut
      CadCut
      Photo
      Open
      RawPart
      Draw
      Import
      CSV
      Simulation
      FrameCut
      Machine
      Alarms
      Options
   End Enum

   Public Function GetExeRootDir() As String
      Return m_sExeRoot
   End Function

   Public Function GetIniFile() As String
      Return m_sIniFile
   End Function

   Public Function GetResourcesDir() As String
      Return m_sResourcesDir
   End Function

   Public Function GetConfigDir() As String
      Return m_sConfigDir
   End Function

   Public Function GetTempDir() As String
      Return m_sTempDir
   End Function

   Public Function GetSaveDir() As String
      Return m_sSaveDir
   End Function

   Public Function GetNamedSaveDir() As String
      Return m_sNamedSaveDir
   End Function

   Public Function GetCopyProjDir() As String
      Return m_sCopyProjDir
   End Function

   Public Function GetVeinMatchingDir() As String
      Return m_sDataRoot & "\" & VEINMATCHING_DIR
   End Function

   Public Function GetCamAutoDir() As String
      Return m_sDataRoot & "\" & CAMAUTO_DIR
   End Function

   Public Function GetCsvAutoDir() As String
      Return m_sDataRoot & "\" & CSVAUTO_DIR
   End Function

   Public Function GetTrfAutoDir() As String
      Return m_sDataRoot & "\" & TRFAUTO_DIR
   End Function

   Public Function GetRuinedPartsDir() As String
      Dim sRuPartsDir As String = String.Empty
      If GetPrivateProfileString(S_CSV, K_RUINEDPARTSDIR, "", sRuPartsDir, m_sIniFile) = 0 Then
         sRuPartsDir = m_sDataRoot & "\" & RUINEDPARTS_DFL_DIR
      End If
      Return sRuPartsDir
   End Function

   Public Function GetCopyTemplateDir() As String
      Return m_sCopyTemplateDir
   End Function

   Public Function GetCncDir() As String
      Return m_sCncDir
   End Function

   Public Function GetMachinesRootDir() As String
      Return m_sMachinesRoot
   End Function

   Public Function GetToolMakersDir() As String
      Return m_sToolMakersDir
   End Function

   Public Function GetCurrMachine() As String
      Return m_sCurrMachine
   End Function

   Public Function GetMachIniFile() As String
      Return m_sMachIniFile
   End Function

   Public Function GetKitsFile() As String
      Return m_sKitsFile
   End Function

   Public Function GetLogFile() As String
      Return m_sLogFile
   End Function

   Friend Function GetKeyLevel() As Integer
      Return m_nKeyLevel
   End Function

   Friend Function GetKeyOption(nKeyOpt As KEY_OPT) As Boolean
      Return ((m_nKeyOptions And nKeyOpt) <> 0)
   End Function

   Friend Function GetKeyOptions() As UInteger
      Return m_nKeyOptions
   End Function

   Friend Function GetAutoNestingOption() As Boolean
      Return m_bAutoNest
   End Function

   Friend Function GetVersion() As String
      Return m_sVersion
   End Function

   Public Function IsSiemensPc() As Boolean
      Return m_bIsSiemensPc
   End Function

   Private Sub MainWindow_Initialized(sender As Object, e As EventArgs) Handles Me.Initialized
      ' Verifico sia l'unica istanza
      ManageSingleIstance()
      ' Imposto path di esecuzione
      m_sExeRoot = System.AppDomain.CurrentDomain.BaseDirectory.TrimEnd("\".ToCharArray())
      ' Impostazione path radice per i dati
      If GetPrivateProfileString(S_DATA, K_DATAROOT, "", m_sDataRoot, m_sExeRoot & "\" & DAT_FILE_NAME) = 0 Then
         m_sDataRoot = m_sExeRoot
      End If
      ' Impostazione direttorio di configurazione
      m_sConfigDir = m_sDataRoot & "\" & CONF_DIR
      ' imposto nella libreria il riferimento del file config
      EgtWPFLib5.IniFile.m_sIniFile = m_sConfigDir & "\" & INI_FILE_NAME
      ' Impostazione direttorio delle risorse
      m_sResourcesDir = m_sDataRoot & "\" & RES_DIR
      ' Impostazione direttorio per file temporanei
      m_sTempDir = m_sDataRoot & "\" & TEMP_DIR
      EgtSetTempDir(m_sTempDir)
      ' Impostazione direttorio per file Cnc
      m_sCncDir = m_sDataRoot & "\" & CNC_DIR
      ' Impostazione path Ini file
      m_sIniFile = m_sConfigDir & "\" & INI_FILE_NAME
      EgtSetIniFile(m_sIniFile)
      ' Impostazione direttorio di salvataggio automatico
      If GetPrivateProfileString(S_GENERAL, K_SAVEDIR, "", m_sSaveDir, m_sIniFile) = 0 Then
         m_sSaveDir = m_sDataRoot & "\" & SAVE_DFL_DIR
      End If
      ' Impostazione direttorio di salvataggio dei progetti con nome
      If GetPrivateProfileString(S_GENERAL, K_SAVENAMEDIR, "", m_sNamedSaveDir, m_sIniFile) = 0 Then
         m_sNamedSaveDir = m_sDataRoot & "\" & SAVE_DFL_NAMEDIR
      End If
      ' Impostazione direttorio di copia dei progetti per modalità Ufficio
      If GetPrivateProfileString(S_GENERAL, K_COPYPROJDIR, "", m_sCopyProjDir, m_sIniFile) = 0 Then
         m_sCopyProjDir = m_sDataRoot & "\" & COPYPROJ_DFL_DIR
      End If
      ' Impostazione direttorio di salvataggio dei DXF delle dime (CopyTemplate)
      If GetPrivateProfileString(S_COPYTEMPLATE, K_CPTCURRDIR, "", m_sCopyTemplateDir, m_sIniFile) = 0 Then
         m_sCopyTemplateDir = m_sDataRoot & "\" & TEMPLATE_DFL_DIR
      End If
      ' Impostazione direttorio per le macchine
      If GetPrivateProfileString(S_MACH, K_MACHINESDIR, "", m_sMachinesRoot, m_sIniFile) = 0 Then
         m_sMachinesRoot = m_sDataRoot & "\" & MACHINES_DFL_DIR
      End If
      ' Impostazione direttorio costruttori di utensili
      If GetPrivateProfileString(S_MACH, K_TOOLMAKERSDIR, "", m_sToolMakersDir, m_sIniFile) = 0 Then
         m_sToolMakersDir = m_sDataRoot & "\" & TOOLMAKERS_DFL_DIR
      End If
      ' Recupero nome macchina corrente
      GetPrivateProfileString(S_MACH, K_CURRMACH, "", m_sCurrMachine, m_sIniFile)
      ' Impostazione path MachIni file
      m_sMachIniFile = m_sMachinesRoot & "\" & m_sCurrMachine & "\" & m_sCurrMachine & ".ini"
      ' Impostazione path KitIni file
      m_sKitsFile = m_sMachinesRoot & "\" & m_sCurrMachine & "\" & MACHININGS_DIR & "\" & KITS_FILE
      ' Imposto tipo di chiave
#If TRIAL Then
      EgtSetLockType(KEY_TYPE.ANY)
#Else
      EgtSetLockType(KEY_TYPE.HW)
#End If
      ' Leggo e imposto chiave di protezione
      Dim sLicFileName As String = String.Empty
      GetPrivateProfileString(S_GENERAL, K_LICENCE, LIC_FILE_NAME, sLicFileName, m_sIniFile)
      Dim sLicFile As String = m_sConfigDir & "\" & sLicFileName
      Dim sKey As String = String.Empty
      GetPrivateProfileString(S_LICENCE, K_KEY, "", sKey, sLicFile)
      EgtSetKey(sKey)
      Dim sNestKey As String = ""
      EgtUILib.GetPrivateProfileString(S_LICENCE, K_NESTKEY, "", sNestKey, sLicFile)
      EgtSetNestKey(sNestKey)
      ' Verifico abilitazione nesting automatico
      m_bAutoNest = Not String.IsNullOrWhiteSpace(sNestKey)
      ' Recupero opzioni della chiave
      Dim bKey As Boolean = EgtGetKeyLevel(9423, 2404, 1, m_nKeyLevel) And
                            EgtGetKeyOptions(9423, 2404, 1, m_nKeyOptions)
      ' Verifico abilitazione prodotto
      Dim bProd As Boolean = GetKeyOption(KEY_OPT.CUT_BASE)
      ' Inizializzazione generale di EgtInterface
      m_nDebug = GetPrivateProfileInt(S_GENERAL, K_DEBUG, 0, m_sIniFile)
      m_sVersion = My.Application.Info.Version.Major.ToString() & "." &
                   My.Application.Info.Version.Minor.ToString() &
                   (ChrW(97 - 1 + My.Application.Info.Version.Build)).ToString() &
                   My.Application.Info.Version.Revision.ToString()
      m_sLogFile = m_sTempDir & "\" & GENLOG_FILE_NAME
      Dim sLogMsg As String = My.Application.Info.Title.ToString() & " ver. " & m_sVersion
      EgtInit(m_nDebug, m_sLogFile, sLogMsg)
      ' Leggo direttorio dei messaggi (se manca uso direttorio di configurazione)
      Dim sMsgDir As String = String.Empty
      If GetPrivateProfileString(S_GENERAL, K_MESSAGESDIR, "", sMsgDir, m_sIniFile) = 0 Then
         sMsgDir = m_sConfigDir
      End If
      ' Leggo elenco lingue disponibili da file ini
      Dim nIndex As Integer = 1
      Dim ReadLanguage As Language = GetPrivateProfileLanguage(S_LANGUAGES, K_LANGUAGE & nIndex, GetIniFile)
      While Not IsNothing(ReadLanguage)
         m_LanguagesList.Add(ReadLanguage)
         nIndex += 1
         ReadLanguage = GetPrivateProfileLanguage(S_LANGUAGES, K_LANGUAGE & nIndex, GetIniFile)
      End While
      ' Leggo file messaggi
      Dim sMsgFile As String = String.Empty
      GetPrivateProfileString(S_GENERAL, K_MESSAGES, "", sMsgFile, m_sIniFile)
      For i As Integer = 0 To m_LanguagesList.Count - 1
         If m_LanguagesList(i).LanguageName = sMsgFile Then
            m_CurrLanguage = m_LanguagesList(i)
         End If
      Next
      Dim sMsgFilePath As String = sMsgDir & "\EgalTechIta.txt"
      If Not IsNothing(m_CurrLanguage) Then
         sMsgFilePath = sMsgDir & "\" & m_CurrLanguage.FileName
      End If
      If Not EgtLoadMessages(sMsgFilePath) Then
         EgtOutLog("Error in EgtLoadMessages")
      End If
      Dim sNfeDir As String = String.Empty
      GetPrivateProfileString(S_GEOMDB, K_NFEFONTDIR, "", sNfeDir, m_sIniFile)
      Dim sDefFont As String = String.Empty
      GetPrivateProfileString(S_GEOMDB, K_DEFAULTFONT, "", sDefFont, m_sIniFile)
      EgtSetFont(sNfeDir, sDefFont)
      ' Imposto dir di default per libreria Lua e lancio libreria di base
      Dim sLuaLibsDir As String = String.Empty
      GetPrivateProfileString(S_LUA, K_LIBSDIR, "", sLuaLibsDir, m_sIniFile)
      EgtSetLuaLibs(sLuaLibsDir)
      Dim sLuaBaseLib As String = String.Empty
      GetPrivateProfileString(S_LUA, K_BASELIB, "EgtBase", sLuaBaseLib, m_sIniFile)
      EgtLuaRequire(sLuaBaseLib)
      ' Imposto unità di misura per interfaccia utente
      Dim bMM As Boolean = (GetPrivateProfileInt(S_GENERAL, K_MMUNITS, 1, m_sIniFile) <> 0)
      EgtSetUiUnits(bMM)
      ' Imposto posizione e dimensioni della MainWindow
      Dim nFlag, nLeft, nTop, nWidth, nHeight As Integer
      GetPrivateProfileWinPos(S_GENERAL, K_WINPLACE, nFlag, nLeft, nTop, nWidth, nHeight, m_sIniFile)
      Me.WindowStartupLocation = Windows.WindowStartupLocation.Manual
      Me.Top = nTop
      Me.Left = nLeft
      Me.Height = If(nHeight = 0, 768, nHeight)
      Me.Width = If(nWidth = 0, 1366, nWidth)
      WindowState = If(nFlag = 1, WindowState.Maximized, WindowState.Normal)
      m_dMWinScale = Math.Min(Me.Width / 1280, Me.Height / 832)
      ' Info su opzioni chiave
      EgtOutLog("KeyOptions : " & bKey.ToString() & " " & m_nKeyOptions.ToString() & " " & bProd.ToString())
      ' Inizializzazione della libreria EgtWPFLib
      EgtWPFInit()
      EgtTextBox.EnableKeybCalc = (GetPrivateProfileInt(S_GENERAL, K_VIRTUALKEYBOARD, 1, m_sIniFile) <> 0)
      ' Inizializzo classe macchina corrente
      m_CurrentMachine = New CurrentMachine
      ' Crezione della MachineStatusBar
      m_MachineStatusUC = New MachineStatusUC
      ' Creazione delle Page UserControl
      m_WorkInProgressPageUC = New WorkInProgressPageUC
      m_DirectCutPageUC = New DirectCutPageUC
      m_CadCutPageUC = New CadCutPageUC
      m_OpenPage = New OpenPageUC
      m_PhotoPage = New PhotoPageUC
      m_RawPartPage = New RawPartPageUC
      m_DrawPageUC = New DrawPageUC
      m_ImportPageUC = New ImportPageUC
      m_SimulationPage = New SimulationPageUC
      m_FrameCutPageUC = New FrameCutPageUC
      m_CurrentProjectPageUC = New CurrentProjectPageUC
      m_MachinePageUC = New MachinePageUC
      m_OptionsPageUC = New OptionsPageUC
      ' Creazione gestore comunicazione con macchina CN
      m_CNCommunication = New CNCommunication
      ' Imposto tipologia di pc su cui gira il programma
      m_bIsSiemensPc = If(GetPrivateProfileInt(S_GENERAL, K_SIEMENSPC, 0, GetIniFile()) = 0, False, True)
      ' Posizionamento nella griglia della MachineStatusBar
      If GetPrivateProfileInt(S_NUMERICALCONTROL, K_TYPE, 0, GetMachIniFile()) = 0 Then
         MainWindowGrid.ColumnDefinitions.RemoveAt(MainWindowGrid.ColumnDefinitions.Count - 1)
         MainWindowGrid.RowDefinitions.RemoveAt(MainWindowGrid.RowDefinitions.Count - 1)
         WorkInProgressBtn.IsEnabled = False
      Else
         If Not m_bIsSiemensPc Then
            m_MachineStatusUC.SetValue(Grid.RowProperty, 2)
            MainWindowGrid.ColumnDefinitions.RemoveAt(MainWindowGrid.ColumnDefinitions.Count - 1)
         Else
            m_MachineStatusUC.SetValue(Grid.ColumnProperty, 2)
            m_MachineStatusUC.SetValue(Grid.RowSpanProperty, 3)
            MainWindowGrid.RowDefinitions.RemoveAt(MainWindowGrid.RowDefinitions.Count - 1)
         End If
      End If

      ' abilito il bottone per la gestione del comando di Check-Up-Start (posziona lama prelavorazione)
      If GetPrivateProfileInt(S_GENERAL, "Test", "0", m_sIniFile) = 0 OrElse
         Not File.Exists( m_CurrentMachine.sMachDir() & "\DirectCmd\TestWork.lua") Then
         m_CadCutPageUC.m_ProjectMgr.TestBtn.Visibility = Visibility.Collapsed
      Else
         m_CadCutPageUC.m_ProjectMgr.TestBtn.Visibility = Visibility.Visible
      End If

      If m_bIsSiemensPc Then
         Application.Current.Resources("FontSize_LowerCaseCharacter") = New FontSizeConverter().ConvertFrom(CStr("17"))
         Application.Current.Resources("ComboBox_Height") = New LengthConverter().ConvertFrom(CStr("35"))
         Application.Current.Resources("FontSize_GroupBoxHeader") = New LengthConverter().ConvertFrom(CStr("19"))
         Application.Current.Resources("CheckBox_Height") = New LengthConverter().ConvertFrom(CStr("35"))
         Application.Current.Resources("TextBoxInGroupBox_Margin") = New Thickness(2, 0, 9, 0)
         Application.Current.Resources("RightTextBoxInBorder_Margin") = New Thickness(1, 0, 12, 0)
         Application.Current.Resources("LeftTextBoxInBorder_Margin") = New Thickness(4, 0, 9, 0)
         Application.Current.Resources("LeftTextBoxNoBorder_Margin") = New Thickness(6, 0, 9, 0)
         Application.Current.Resources("RightComboBoxInBorder_Margin") = New Thickness(2, 0, 11, 0)
         Application.Current.Resources("MachRightTextBoxInBorder_Margin") = New Thickness(2, 0, 11, 0)
         Application.Current.Resources("MachLeftTextBoxInBorder_Margin") = New Thickness(4, 0, 9, 0)
         Application.Current.Resources("LeftComboBoxInBorder_Margin") = New Thickness(4, 0, 9, 0)
         Application.Current.Resources("MachToolLeftTextBoxNoBorder_Margin") = New Thickness(3, 0, 15, 0)
         Application.Current.Resources("ArrowImage_Height") = New LengthConverter().ConvertFrom(CStr("52"))
         Application.Current.Resources("ScaleImage_Height") = New LengthConverter().ConvertFrom(CStr("60"))
         Application.Current.Resources("MachineStatusImage_Height") = New LengthConverter().ConvertFrom(CStr("65"))
         Application.Current.Resources("SplitPageBtn_FontSize") = New LengthConverter().ConvertFrom(CStr("14"))
      End If
      ' Posizionemento nella griglia delle Page UserControl
      m_WorkInProgressPageUC.SetValue(Grid.ColumnProperty, 0)
      m_WorkInProgressPageUC.SetValue(Grid.RowProperty, 1)
      m_OpenPage.SetValue(Grid.ColumnProperty, 0)
      m_OpenPage.SetValue(Grid.RowProperty, 1)
      m_PhotoPage.SetValue(Grid.ColumnProperty, 0)
      m_PhotoPage.SetValue(Grid.RowProperty, 1)
      m_RawPartPage.SetValue(Grid.ColumnSpanProperty, 2)
      m_RawPartPage.SetValue(Grid.RowSpanProperty, 3)
      m_SimulationPage.SetValue(Grid.ColumnSpanProperty, 2)
      m_SimulationPage.SetValue(Grid.RowSpanProperty, 3)
      m_DrawPageUC.SetValue(Grid.ColumnProperty, 0)
      m_DrawPageUC.SetValue(Grid.RowProperty, 1)
      m_ImportPageUC.SetValue(Grid.ColumnProperty, 0)
      m_ImportPageUC.SetValue(Grid.RowProperty, 1)
      m_CurrentProjectPageUC.SetValue(Grid.ColumnProperty, 0)
      m_CurrentProjectPageUC.SetValue(Grid.RowProperty, 1)
      m_MachinePageUC.SetValue(Grid.ColumnProperty, 0)
      m_MachinePageUC.SetValue(Grid.RowProperty, 1)
      m_OptionsPageUC.SetValue(Grid.ColumnProperty, 0)
      m_OptionsPageUC.SetValue(Grid.RowProperty, 1)
      ' Posizionamento nella griglia di pagine e usercontrol di utilità
      m_WorkInProgressPageUC.SetValue(Grid.ColumnProperty, 0)
      m_WorkInProgressPageUC.SetValue(Grid.RowProperty, 1)
      ' Disabilita la possibilità di imitare il click del tasto destro del mouse tenendo premuto il dito sul touch
      ' NB: Se abilitato impedisce di utilizzare lo stato Pressed dei Button che quindi non si evidenziano quando premuti
      Stylus.SetIsPressAndHoldEnabled(Me, False)
      ' Imposto i messaggi letti dal file dei messaggi
      WorkInProgressBtn.Content = EgtMsg(MSG_GENERAL + 1)
      DirectCutBtn.Content = EgtMsg(MSG_GENERAL + 2)
      CadCutBtn.Content = EgtMsg(MSG_GENERAL + 3)
      FrameCutBtn.Content = EgtMsg(MSG_GENERAL + 4)
      MachineBtn.Content = EgtMsg(MSG_GENERAL + 5)
      ' Imposto OnIdle
      AddHandler m_IdleTimer.Tick, AddressOf OnIdle
      ' Imposto OnProdLine
      AddHandler m_ProdLineTimer.Tick, AddressOf OnProdLine
      ' Imposto riferimento a funzione delle textbox che disattiva scene in libreria
      EgtWPFLib.EgtTextBox.m_refScenesIsEnabled = AddressOf IsEnabledScenes
   End Sub

   Private Sub ManageSingleIstance()
      Dim bCreated As Boolean
      Try
         m_objMutex = New Mutex(False, "Global\OmagCut", bCreated)
      Catch
         bCreated = False
      End Try
      If Not bCreated Then
         ' porto in primo piano la prima istanza
         Dim bFound As Boolean = False
         ' processi del programma a 32 bit
         Dim localProc As Process() = Process.GetProcessesByName("OmagCutR32")
         For Each p As Process In localProc
            If p.Id <> Process.GetCurrentProcess().Id Then
               bFound = True
               ShowWindow(p.MainWindowHandle, 1)
               Exit For
            End If
         Next
         ' se non trovati processi a 32 bit provo a 64 bit
         If Not bFound Then
            localProc = Process.GetProcessesByName("OmagCutR64")
            For Each p As Process In localProc
               If p.Id <> Process.GetCurrentProcess().Id Then
                  bFound = True
                  ShowWindow(p.MainWindowHandle, SW.RESTORE)
                  Exit For
               End If
            Next
         End If
         ' esco dal programma
         End
      End If
   End Sub

   Private Sub MainWindow_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs) Handles Me.Loaded
      ' Se il controllo numerico non è impostato a 0
      If Not GetPrivateProfileInt(S_NUMERICALCONTROL, K_TYPE, 0, GetMachIniFile()) = 0 Then
         ' Aggiungo la MachineStatusBar alla MainWindow
         MainWindowGrid.Children.Add(m_MachineStatusUC)
      End If

      ' Preparo la macchina per la lavorazione in corso
      m_WorkInProgressPageUC.Prepare()
      m_WorkInProgressPageUC.UpdateTools()

      ' Se macchina fotografica abilitata, ne inizializzo il gestore
#If Not TRIAL Then
      If GetKeyOption(MainWindow.KEY_OPT.MAN_PHOTO) Then
         m_Camera.Init()
      End If
#End If

      ' Seleziono la Page di apertura
      MainWindowGrid.Children.Add(m_CurrentProjectPageUC)

      ' Lancio timer per aggiornamento interfaccia
      m_IdleTimer.Interval = TimeSpan.FromMilliseconds(100)
      m_IdleTimer.Start()

      ' inizilizzo
   End Sub

#Region "Selezione dei bottoni IN LAVORO, TAGLII DIRETTI, TAGLI CAD, CORNICI, MACCHINA, OPZIONI"

   Private Sub WorkInProgressBtn_Click(sender As Object, e As RoutedEventArgs) Handles WorkInProgressBtn.Click
      m_CurrentProjectPageUC.m_SceneButtons.MeasureBtn.IsChecked = False
      ' disbilito Test
      TestOff()
      ' disabilito DragRettangle
      DragRettangleOff()
      Select Case m_ActivePage
         Case Pages.WorkInProgress
            WorkInProgressBtn.IsChecked = True
         Case Pages.DirectCut
            WorkInProgressBtn.IsChecked = True
            DirectCutBtn.IsChecked = False
            EgtMdbSetGeneralParam(MCH_GP.SAFEZ, DirectCutPageUC.m_dZSafe)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Remove(m_DirectCutPageUC)
            MainWindowGrid.Children.Remove(m_CurrentProjectPageUC)
            MainWindowGrid.Children.Add(m_WorkInProgressPageUC)
            m_ActivePage = Pages.WorkInProgress
         Case Pages.CadCut And (m_CadCutPageUC.m_CadCutMode = CadCutPageUC.CadCutModes.Nest Or m_CadCutPageUC.m_CadCutMode = CadCutPageUC.CadCutModes.FastGrid) And Not m_CadCutPageUC.m_NestPage.m_bRegister
            WorkInProgressBtn.IsChecked = True
            CadCutBtn.IsChecked = False
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Remove(m_CadCutPageUC)
            MainWindowGrid.Children.Remove(m_CurrentProjectPageUC)
            MainWindowGrid.Children.Add(m_WorkInProgressPageUC)
            m_ActivePage = Pages.WorkInProgress
         Case Pages.Photo, Pages.RawPart, Pages.Draw, Pages.Import, Pages.CSV,
              Pages.CadCut And (m_CadCutPageUC.m_CadCutMode <> CadCutPageUC.CadCutModes.Nest Or m_CadCutPageUC.m_NestPage.m_bRegister)
            ' Pages.Simulation: prma era inserito nell'elenco -> prima di procedere devo uscire dalla pagina della simulazione
            WorkInProgressBtn.IsChecked = False
            CadCutBtn.IsChecked = True
         Case Pages.FrameCut
            WorkInProgressBtn.IsChecked = True
            FrameCutBtn.IsChecked = False
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Remove(m_FrameCutPageUC)
            MainWindowGrid.Children.Remove(m_CurrentProjectPageUC)
            MainWindowGrid.Children.Add(m_WorkInProgressPageUC)
            m_ActivePage = Pages.WorkInProgress
         Case Pages.Machine
            WorkInProgressBtn.IsChecked = False
            If Not ExitFromMachine() Then
               WorkInProgressBtn.IsChecked = False
               MachineBtn.IsChecked = True
               Exit Sub
            End If
            WorkInProgressBtn.IsChecked = True
            MachineBtn.IsChecked = False
            MainWindowGrid.Children.Remove(m_MachinePageUC)
            MainWindowGrid.Children.Add(m_WorkInProgressPageUC)
            m_ActivePage = Pages.WorkInProgress
         Case Pages.Options
            WorkInProgressBtn.IsChecked = True
            OptionsBtn.IsChecked = False
            MainWindowGrid.Children.Remove(m_OptionsPageUC)
            MainWindowGrid.Children.Add(m_WorkInProgressPageUC)
            m_ActivePage = Pages.WorkInProgress
      End Select
   End Sub

   Private Sub DirectCutBtn_Click(sender As Object, e As RoutedEventArgs) Handles DirectCutBtn.Click
      ' carico la quota di svincolo di sicurezza dell'utensile
      EgtMdbGetGeneralParam(MCH_GP.SAFEZ, DirectCutPageUC.m_dZSafe)
      m_CurrentProjectPageUC.m_SceneButtons.MeasureBtn.IsChecked = False
      TestOff()
      DragRettangleOff()
      Select Case m_ActivePage
         Case Pages.WorkInProgress
            WorkInProgressBtn.IsChecked = False
            DirectCutBtn.IsChecked = True
            MainWindowGrid.Children.Remove(m_WorkInProgressPageUC)
            MainWindowGrid.Children.Add(m_CurrentProjectPageUC)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Add(m_DirectCutPageUC)
            m_ActivePage = Pages.DirectCut
         Case Pages.DirectCut
            DirectCutBtn.IsChecked = True
         Case Pages.CadCut And (m_CadCutPageUC.m_CadCutMode = CadCutPageUC.CadCutModes.Nest Or m_CadCutPageUC.m_CadCutMode = CadCutPageUC.CadCutModes.FastGrid) And Not m_CadCutPageUC.m_NestPage.m_bRegister
            DirectCutBtn.IsChecked = True
            CadCutBtn.IsChecked = False
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Remove(m_CadCutPageUC)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Add(m_DirectCutPageUC)
            m_ActivePage = Pages.DirectCut
         Case Pages.Photo, Pages.RawPart, Pages.Draw, Pages.Import, Pages.CSV,
              Pages.CadCut And (m_CadCutPageUC.m_CadCutMode <> CadCutPageUC.CadCutModes.Nest Or m_CadCutPageUC.m_NestPage.m_bRegister)
            ' Pages.Simulation: prma era inserito nell'elenco -> prima di procedere devo uscire dalla pagina della simulazione
            DirectCutBtn.IsChecked = False
            CadCutBtn.IsChecked = True
         Case Pages.FrameCut
            DirectCutBtn.IsChecked = True
            FrameCutBtn.IsChecked = False
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Remove(m_FrameCutPageUC)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Add(m_DirectCutPageUC)
            m_ActivePage = Pages.DirectCut
         Case Pages.Machine
            DirectCutBtn.IsChecked = False
            If Not ExitFromMachine() Then
               DirectCutBtn.IsChecked = False
               MachineBtn.IsChecked = True
               Exit Sub
            End If
            DirectCutBtn.IsChecked = True
            MachineBtn.IsChecked = False
            MainWindowGrid.Children.Remove(m_MachinePageUC)
            MainWindowGrid.Children.Add(m_CurrentProjectPageUC)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Add(m_DirectCutPageUC)
            m_ActivePage = Pages.DirectCut
         Case Pages.Options
            DirectCutBtn.IsChecked = True
            OptionsBtn.IsChecked = False
            MainWindowGrid.Children.Remove(m_OptionsPageUC)
            MainWindowGrid.Children.Add(m_CurrentProjectPageUC)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Add(m_DirectCutPageUC)
            m_ActivePage = Pages.DirectCut
      End Select
   End Sub

   Private Sub CadCutBtn_Click(sender As Object, e As RoutedEventArgs) Handles CadCutBtn.Click
      m_CurrentProjectPageUC.m_SceneButtons.MeasureBtn.IsChecked = False
      TestOff()
      DragRettangleOff()
      Select Case m_ActivePage
         Case Pages.WorkInProgress
            WorkInProgressBtn.IsChecked = False
            CadCutBtn.IsChecked = True
            MainWindowGrid.Children.Remove(m_WorkInProgressPageUC)
            MainWindowGrid.Children.Add(m_CurrentProjectPageUC)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Add(m_CadCutPageUC)
            m_ActivePage = Pages.CadCut
         Case Pages.DirectCut
            DirectCutBtn.IsChecked = False
            CadCutBtn.IsChecked = True
            EgtMdbSetGeneralParam(MCH_GP.SAFEZ, DirectCutPageUC.m_dZSafe)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Remove(m_DirectCutPageUC)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Add(m_CadCutPageUC)
            m_ActivePage = Pages.CadCut
         Case Pages.CadCut
            CadCutBtn.IsChecked = True
         Case Pages.Photo, Pages.RawPart, Pages.Draw, Pages.Import, Pages.CSV
            ' Pages.Simulation: prma era inserito nell'elenco -> prima di procedere devo uscire dalla pagina della simulazione
            CadCutBtn.IsChecked = True
         Case Pages.FrameCut
            CadCutBtn.IsChecked = True
            FrameCutBtn.IsChecked = False
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Remove(m_FrameCutPageUC)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Add(m_CadCutPageUC)
            m_ActivePage = Pages.CadCut
         Case Pages.Machine
            CadCutBtn.IsChecked = False
            If Not ExitFromMachine() Then
               CadCutBtn.IsChecked = False
               MachineBtn.IsChecked = True
               Exit Sub
            End If
            CadCutBtn.IsChecked = True
            MachineBtn.IsChecked = False
            MainWindowGrid.Children.Remove(m_MachinePageUC)
            MainWindowGrid.Children.Add(m_CurrentProjectPageUC)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Add(m_CadCutPageUC)
            m_ActivePage = Pages.CadCut
         Case Pages.Options
            CadCutBtn.IsChecked = True
            OptionsBtn.IsChecked = False
            MainWindowGrid.Children.Remove(m_OptionsPageUC)
            MainWindowGrid.Children.Add(m_CurrentProjectPageUC)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Add(m_CadCutPageUC)
            m_ActivePage = Pages.CadCut
      End Select
   End Sub

   Private Sub FrameCutBtn_Click(sender As Object, e As RoutedEventArgs) Handles FrameCutBtn.Click
      m_CurrentProjectPageUC.m_SceneButtons.MeasureBtn.IsChecked = False
      TestOff()
      DragRettangleOff()
      Select Case m_ActivePage
         Case Pages.WorkInProgress
            WorkInProgressBtn.IsChecked = False
            FrameCutBtn.IsChecked = True
            EgtMdbSetGeneralParam(MCH_GP.SAFEZ, DirectCutPageUC.m_dZSafe)
            MainWindowGrid.Children.Remove(m_WorkInProgressPageUC)
            MainWindowGrid.Children.Add(m_CurrentProjectPageUC)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Add(m_FrameCutPageUC)
            m_ActivePage = Pages.FrameCut
         Case Pages.DirectCut
            DirectCutBtn.IsChecked = False
            FrameCutBtn.IsChecked = True
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Remove(m_DirectCutPageUC)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Add(m_FrameCutPageUC)
            m_ActivePage = Pages.FrameCut
         Case Pages.CadCut
            CadCutBtn.IsChecked = False
            FrameCutBtn.IsChecked = True
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Remove(m_CadCutPageUC)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Add(m_FrameCutPageUC)
            m_ActivePage = Pages.FrameCut
         Case Pages.Photo, Pages.RawPart, Pages.Draw, Pages.Import, Pages.CSV
            ' Pages.Simulation: quando sono nella simulazione devo uscire dalla pagina
            CadCutBtn.IsChecked = False
            FrameCutBtn.IsChecked = True
         Case Pages.FrameCut
            FrameCutBtn.IsChecked = True
         Case Pages.Machine
            FrameCutBtn.IsChecked = False
            If Not ExitFromMachine() Then
               FrameCutBtn.IsChecked = False
               MachineBtn.IsChecked = True
               Exit Sub
            End If
            FrameCutBtn.IsChecked = True
            MachineBtn.IsChecked = False
            MainWindowGrid.Children.Remove(m_MachinePageUC)
            MainWindowGrid.Children.Add(m_CurrentProjectPageUC)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Add(m_FrameCutPageUC)
            m_ActivePage = Pages.FrameCut
         Case Pages.Options
            FrameCutBtn.IsChecked = True
            OptionsBtn.IsChecked = False
            MainWindowGrid.Children.Remove(m_OptionsPageUC)
            MainWindowGrid.Children.Add(m_CurrentProjectPageUC)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Add(m_FrameCutPageUC)
            m_ActivePage = Pages.FrameCut
      End Select
   End Sub

   Private Sub MachineBtn_Click(sender As Object, e As RoutedEventArgs) Handles MachineBtn.Click
      m_CurrentProjectPageUC.m_SceneButtons.MeasureBtn.IsChecked = False
      TestOff()
      DragRettangleOff()
      Select Case m_ActivePage
         Case Pages.WorkInProgress
            WorkInProgressBtn.IsChecked = False
            MachineBtn.IsChecked = True
            MainWindowGrid.Children.Remove(m_WorkInProgressPageUC)
            MainWindowGrid.Children.Add(m_MachinePageUC)
            m_ActivePage = Pages.Machine
         Case Pages.DirectCut
            DirectCutBtn.IsChecked = False
            MachineBtn.IsChecked = True
            EgtMdbSetGeneralParam(MCH_GP.SAFEZ, DirectCutPageUC.m_dZSafe)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Remove(m_DirectCutPageUC)
            MainWindowGrid.Children.Remove(m_CurrentProjectPageUC)
            MainWindowGrid.Children.Add(m_MachinePageUC)
            m_ActivePage = Pages.Machine
         Case Pages.CadCut And (m_CadCutPageUC.m_CadCutMode = CadCutPageUC.CadCutModes.Nest Or m_CadCutPageUC.m_CadCutMode = CadCutPageUC.CadCutModes.FastGrid) And Not m_CadCutPageUC.m_NestPage.m_bRegister
            CadCutBtn.IsChecked = False
            MachineBtn.IsChecked = True
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Remove(m_CadCutPageUC)
            MainWindowGrid.Children.Remove(m_CurrentProjectPageUC)
            MainWindowGrid.Children.Add(m_MachinePageUC)
            m_ActivePage = Pages.Machine
         Case Pages.Photo, Pages.RawPart, Pages.Draw, Pages.Import, Pages.CSV,
              Pages.CadCut And (m_CadCutPageUC.m_CadCutMode <> CadCutPageUC.CadCutModes.Nest Or m_CadCutPageUC.m_NestPage.m_bRegister)
            ' Pages.Simulation: prma era inserito nell'elenco -> prima di procedere devo uscire dalla pagina della simulazione
            CadCutBtn.IsChecked = True
            MachineBtn.IsChecked = False
         Case Pages.FrameCut
            FrameCutBtn.IsChecked = False
            MachineBtn.IsChecked = True
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Remove(m_FrameCutPageUC)
            MainWindowGrid.Children.Remove(m_CurrentProjectPageUC)
            MainWindowGrid.Children.Add(m_MachinePageUC)
            m_ActivePage = Pages.Machine
         Case Pages.Machine
            MachineBtn.IsChecked = True
         Case Pages.Options
            MachineBtn.IsChecked = True
            OptionsBtn.IsChecked = False
            MainWindowGrid.Children.Remove(m_OptionsPageUC)
            MainWindowGrid.Children.Add(m_MachinePageUC)
            m_ActivePage = Pages.Machine
      End Select
   End Sub

   Private Sub OptionsBtn_Click(sender As Object, e As RoutedEventArgs) Handles OptionsBtn.Click
      m_CurrentProjectPageUC.m_SceneButtons.MeasureBtn.IsChecked = False
      TestOff()
      DragRettangleOff()
      Select Case m_ActivePage
         Case Pages.WorkInProgress
            WorkInProgressBtn.IsChecked = False
            OptionsBtn.IsChecked = True
            MainWindowGrid.Children.Remove(m_WorkInProgressPageUC)
            MainWindowGrid.Children.Add(m_OptionsPageUC)
            m_ActivePage = Pages.Options
         Case Pages.DirectCut
            DirectCutBtn.IsChecked = False
            OptionsBtn.IsChecked = True
            EgtMdbSetGeneralParam(MCH_GP.SAFEZ, DirectCutPageUC.m_dZSafe)
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Remove(m_DirectCutPageUC)
            MainWindowGrid.Children.Remove(m_CurrentProjectPageUC)
            MainWindowGrid.Children.Add(m_OptionsPageUC)
            m_ActivePage = Pages.Options
         Case Pages.CadCut And (m_CadCutPageUC.m_CadCutMode = CadCutPageUC.CadCutModes.Nest Or m_CadCutPageUC.m_CadCutMode = CadCutPageUC.CadCutModes.FastGrid) And Not m_CadCutPageUC.m_NestPage.m_bRegister
            CadCutBtn.IsChecked = False
            OptionsBtn.IsChecked = True
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Remove(m_CadCutPageUC)
            MainWindowGrid.Children.Remove(m_CurrentProjectPageUC)
            MainWindowGrid.Children.Add(m_OptionsPageUC)
            m_ActivePage = Pages.Options
         Case Pages.Photo, Pages.RawPart, Pages.Draw, Pages.Import, Pages.CSV,
              Pages.CadCut And (m_CadCutPageUC.m_CadCutMode <> CadCutPageUC.CadCutModes.Nest Or m_CadCutPageUC.m_NestPage.m_bRegister)
            ' Pages.Simulation: prma era inserito nell'elenco -> prima di procedere devo uscire dalla pagina della simulazione
            CadCutBtn.IsChecked = True
            OptionsBtn.IsChecked = False
         Case Pages.FrameCut
            FrameCutBtn.IsChecked = False
            OptionsBtn.IsChecked = True
            m_CurrentProjectPageUC.CurrentProjectPageGrid.Children.Remove(m_FrameCutPageUC)
            MainWindowGrid.Children.Remove(m_CurrentProjectPageUC)
            MainWindowGrid.Children.Add(m_OptionsPageUC)
            m_ActivePage = Pages.Options
         Case Pages.Machine
            OptionsBtn.IsChecked = False
            If Not ExitFromMachine() Then
               OptionsBtn.IsChecked = False
               MachineBtn.IsChecked = True
               Exit Sub
            End If
            MachineBtn.IsChecked = False
            OptionsBtn.IsChecked = True
            MainWindowGrid.Children.Remove(m_MachinePageUC)
            MainWindowGrid.Children.Add(m_OptionsPageUC)
            m_ActivePage = Pages.Options
         Case Pages.Options
            OptionsBtn.IsChecked = True
      End Select
   End Sub

#End Region    ' Selezione dei bottoni IN LAVORO, TAGLII DIRETTI, TAGLI CAD, CORNICI, MACCHINA, OPZIONI

   Private Sub MainWindow_PreviewMouseDown(sender As Object, e As MouseButtonEventArgs) Handles Me.PreviewMouseDown
      ' Se sto fotografando, impedisco tutte le operazioni
      If m_Camera.m_bBusy And Not m_CurrentProjectPageUC.m_SceneButtons.IsMouseOver Then
         e.Handled = True
         Return
      End If
      ' Se già visualizzato errore, lo nascondo
      If m_CurrentProjectPageUC.OutMessageBrd.IsMouseOver Then
         m_CurrentProjectPageUC.ClearMessage()
      End If
      ' Condizioni che impediscono di clickare fuori dalla calcolatrice o tastiera quando una di queste è aperta
      If EgtWPFLib.EgtCalculator.GetbIsActive Then
         e.Handled = True
         Return
      End If
      If EgtWPFLib.EgtKeyboard.GetbIsActive Then
         e.Handled = True
         Return
      End If
   End Sub

   Private Sub MainWindow_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
      'If (m_NumericKeyboardWD.IsVisible And e.Key = Key.Enter) Then
      '    m_NumericKeyboardWD.Visibility = Windows.Visibility.Hidden
      'End If
   End Sub

   Private Sub ExitBtn_Click(sender As Object, e As RoutedEventArgs)
      ' Se premuto Shift si fa minimizzazione
      If (Keyboard.Modifiers And ModifierKeys.Shift) > 0 Then
         Me.WindowState = Windows.WindowState.Minimized
         Return
      End If
      ' Lancio la chiusura
      Me.Close()
   End Sub

   Private Sub MyClosing(sender As Object, e As CancelEventArgs) Handles Me.Closing
      ' Verifico se stato simulazione consente di uscire
      If m_SimulationPage.GetSimExecuting() Then
         e.Cancel = True
         Return
      End If
      ' Verifica se progetto corrente da salvare
      Dim bPrjToSave As Boolean = False
      EgtSetCurrentContext(m_CurrentProjectPageUC.CurrentProjectScene.GetCtx())
      If EgtGetModified() Then
         Dim SaveCurrProj As EgtMsgBox
         If IsSiemensPc() Then
            SaveCurrProj = New EgtMsgBox(Me, Me.ActualWidth / 17 * 5, EgtMsgBox.WidthType.PIXEL, "", EgtMsg(MSG_EGTMSGBOX + 1), EgtMsgBox.Buttons.YES_NO_CANCEL, EgtMsgBox.Icons.NULL)
         Else
            SaveCurrProj = New EgtMsgBox(Me, "", EgtMsg(MSG_EGTMSGBOX + 1), EgtMsgBox.Buttons.YES_NO_CANCEL, EgtMsgBox.Icons.NULL)
         End If
         Select Case SaveCurrProj.m_nPressedBtn
            Case 0    ' Annulla
               e.Cancel = True
               Return
            Case 1    ' Si
               bPrjToSave = True
            Case 2    ' No
               bPrjToSave = False
         End Select
      End If
      ' Uscita da pagina corrente definizione grezzo
      If Not ExitFromRaw() Then
         e.Cancel = True
         Return
      End If
      ' Uscita da pagina corrente CSV
      If Not ExitFromCsv() Then
         e.Cancel = True
         Return
      End If
      ' Uscita da pagina corrente di split
      If Not ExitFromSplit() Then
         e.Cancel = True
         Return
      End If
      ' Uscita da pagina corrente di simulazione
      If Not ExitFromSimulation() Then
         e.Cancel = True
         Return
      End If
      ' Uscita da pagina corrente di macchina
      If Not ExitFromMachine() Then
         e.Cancel = True
         Return
      End If
      ' Uscita da pagina tagli diretti
      If Not ExitFromDirectCut(sender, Nothing) Then
         e.Cancel = True
         Return
      End If
      ' Eventuale salvataggio progetto corrente
      If bPrjToSave Then
         EgtSetCurrentContext(m_CurrentProjectPageUC.CurrentProjectScene.GetCtx())
         m_CurrentProjectPageUC.SaveNamedProject()
         m_CurrentProjectPageUC.SaveProject()
      End If
      ' Uscita
      MainWindowExit()
   End Sub

#Region "Uscita dalle pagine RAW, CSV, SPLIT, SIMULATION, TAGLI DIRETTI, MACCHINA, MAINWINDOW"

   Private Function ExitFromRaw() As Boolean
      ' Se non sono in definizione grezzo tutto ok
      If m_ActivePage <> Pages.RawPart Then Return True
      ' Mi assicuro di terminare correttamente le operazioni
      Return m_RawPartPage.ExitRawPart(True)
   End Function

   Private Function ExitFromCsv() As Boolean
      ' Salvo lo stato attuale della lista
      m_CadCutPageUC.m_CSVPage.SaveCsvPartList()
      Return True
   End Function

   Private Function ExitFromSplit() As Boolean
      ' Se non sono in split tutto ok
      If m_ActivePage <> Pages.CadCut Or m_CadCutPageUC.m_CadCutMode = CadCutPageUC.CadCutModes.Nest Then Return True
      ' Mi assicuro di terminare correttamente lo split
      m_CadCutPageUC.m_SplitPage.ExitSplit()
      Return True
   End Function

   Private Function ExitFromSimulation() As Boolean
      ' Se non sono in simulazione tutto ok
      If m_ActivePage <> Pages.Simulation Then Return True
      EgtMdbSetGeneralParam(MCH_GP.SAFEZ, DirectCutPageUC.m_dZSafe)
      EgtMdbSave()
      ' Mi assicuro di terminare correttamente la simulazione
      m_SimulationPage.ResetSimulation()
      Return True
   End Function

   Private Function ExitFromDirectCut(sender As Object, e As RoutedEventArgs) As Boolean
      ' Se non sono in tagli diretti tutto ok
      If m_ActivePage <> Pages.DirectCut Then Return True
      ' Concludo le attività in corso
      Select Case m_DirectCutPageUC.m_ActiveDirectCutPage
         Case DirectCutPageUC.DirectCutPages.SingleCut
            m_DirectCutPageUC.m_SingleCut.SingleCut_Unloaded(sender, e)
         Case DirectCutPageUC.DirectCutPages.MultipleCut
            m_DirectCutPageUC.m_MultipleCut.MultipleCut_Unloaded(sender, e)
         Case DirectCutPageUC.DirectCutPages.GridCut
            m_DirectCutPageUC.m_GridCut.GridCut_Unloaded(sender, e)
         Case DirectCutPageUC.DirectCutPages.CopyTemplate
            m_DirectCutPageUC.m_CopyTemplate.CopyTemplate_Unloaded(sender, e)
         Case DirectCutPageUC.DirectCutPages.FlatteningCut
            m_DirectCutPageUC.m_FlatteningCut.FlatteningCut_Unloaded(sender, e)
         Case DirectCutPageUC.DirectCutPages.SawTest
            m_DirectCutPageUC.m_SawTest.SawTest_Unloaded(sender, e)
      End Select
      Return True
   End Function

   Private Function ExitFromMachine() As Boolean
      ' Se non sono in machine tutto ok
      If m_ActivePage <> Pages.Machine Then Return True
      ' Concludo le attività in corso
      Select Case m_MachinePageUC.m_ActiveMachinePage
         Case MachinePageUC.MachinePages.Alarms
         Case MachinePageUC.MachinePages.ToolsDb
            ' Verifica ed eventuale salvataggio utensile corrente
            If Not m_MachinePageUC.m_ToolsDbPageUC.SaveCurrTool() Then
               Return False
            End If
            ' salvo il DB utensili
            EgtSetCurrentContext(m_CurrentProjectPageUC.CurrentProjectScene.GetCtx())
            EgtTdbSave()
         Case MachinePageUC.MachinePages.MachiningDb
            ' Verifica ed eventuale salvataggio lavorazione corrente
            If Not m_MachinePageUC.m_MachiningDbPageUC.SaveCurrMachining() Then
               Return False
            End If
            ' salvo il DB utensili
            EgtSetCurrentContext(m_CurrentProjectPageUC.CurrentProjectScene.GetCtx())
            EgtMdbSave()
         Case MachinePageUC.MachinePages.Polishings
            ' Verifica ed eventuale salvataggio lucidatura corrente
            If Not m_MachinePageUC.m_PolishingsPageUC.SaveKit() Then
               Return False
            End If
         Case MachinePageUC.MachinePages.WaterJet
            ' Verifica ed eventuale salvataggio Db Waterjet
            Dim m_MainWindow As MainWindow = DirectCast(Application.Current.MainWindow, MainWindow)
            Dim nPressedBtn As Integer = DirectCast(m_MachinePageUC.m_WaterJetPageUC.DataContext, EgtWPFLib5.WaterjetDbWindowVM).CloseWaterjetDb_OmagCut(m_MainWindow)
            If nPressedBtn = EgtWPFLib5.WaterjetDbWindowVM.SaveWndBtnEnum.CANCEL Then
               Return False
            ElseIf nPressedBtn = EgtWPFLib5.WaterjetDbWindowVM.SaveWndBtnEnum.NO Then
               m_MachinePageUC.m_WaterJetPageUC.WaterJetPage_Reinitialize()
            End If
      End Select
      Return True
   End Function

   Private Sub MainWindowExit()
      ' Chiudo comunicazione con CN
      If Not IsNothing(m_CNCommunication.m_CN) Then m_CNCommunication.m_CN.Stop_Connection()
      ' Chiudo il gestore della macchina fotografica
      m_Camera.Close()
      ' Terminazione generale di EgtInterface
      EgtExit()
      ' Rilascio mutex
      m_objMutex.Close()
   End Sub

#End Region    ' Uscita dalle pagine RAW, CSV, SPLIT, SIMULATION, TAGLI DIRETTI, MACCHINA, MAINWINDOW

   Private Sub MainWindow_ContentRendered(sender As Object, e As EventArgs) Handles Me.ContentRendered
      ' Verifico presenza del collegamento al CN
      m_bNCLink = (GetPrivateProfileInt(S_GENERAL, K_CNLINK, 0, m_sIniFile) <> 0) And
                  Not GetKeyOption( KEY_OPT.OFFICE_TYPE)
      m_CNCommunication.CNCommunication_Initialization()
      ' Se linea di produzione abilitata e collegata, lancio relativo timer
      If m_bNCLink And m_CurrentMachine.bProdLine Then
         m_ProdLineTimer.Interval = TimeSpan.FromMilliseconds(2000)
         m_ProdLineTimer.Start()
      ElseIf m_CurrentMachine.bDemo Then
         m_ProdLineTimer.Interval = TimeSpan.FromMilliseconds(2000)
         m_ProdLineTimer.Start()
      End If

      ' seleziono il tipo di avvio
      m_CurrentProjectPageUC.StartProgram()
      ' aggiorno la grafica
      EgtZoom(ZM.ALL, True)
   End Sub

   Friend Sub EgtWPFInit()
      'EgtBasicInfo
      EgtWPFLib.InitializeEgtWPFLib.EgtBasicInfo_Initialization("C:/EgtDev/OmagCUT",
                                                                1280, 1024, 15, 12,
                                                                "/#Century Gothic",
                                                                "/gothic.ttf",
                                                                Application.Current.FindResource("FontSize_UpperCaseCharacter"),
                                                                Application.Current.FindResource("FontSize_LowerCaseCharacter"),
                                                                GetPrivateProfileInt(S_GENERAL, K_THEME, 0, GetIniFile()))
      ' EgtMessageBox
      EgtWPFLib.InitializeEgtWPFLib.EgtMsgBox_Initialization(Application.Current.FindResource("OmagCut_WindowBorder"),
                                                             Application.Current.FindResource("OmagCut_WindowGrayTextButton"),
                                                             Nothing,
                                                             Application.Current.FindResource("FontSize_UpperCaseCharacter"),
                                                             Application.Current.FindResource("FontSize_LowerCaseCharacter"))
      'Inizializzazione della libreria
      EgtWPFLib.InitializeEgtWPFLib.EgtPaths_Initialization()
   End Sub

   ' OnIdle
   Private Sub OnIdle()
      ' Recupero il tipo di progetto
      Dim nPrjType As Integer = m_CurrentProjectPageUC.GetCurrentProjectType()
      ' Aggiorno interfaccia
      CadCutBtn.IsEnabled = (nPrjType <> CurrentProjectPageUC.PRJ_TYPE.FRAMES)
      FrameCutBtn.IsEnabled = (nPrjType <> CurrentProjectPageUC.PRJ_TYPE.FLATS) AndAlso (EgtGetHeadId("H1") <> GDB_ID.NULL)
      ' DirectCutBtn.IsEnabled = (EgtGetHeadId("H1") <> GDB_ID.NULL)
   End Sub

   ' Nomi dei file per OmagVIEW
   Const CURR_PROJ_NGE As String = "CurrProj.nge"
   Const CURR_PROJ_JPG As String = "CurrProj.jpg"
   Const CURR_PROJ_NEW As String = "CurrProj.new"
   ' Nomi dei file da OmagVIEW
   Const CURR_PROJ_LOCK As String = "CurrProj.lck"
   Const CURR_PROJ_CHANGE As String = "CurrProj.chg"
   Const CURR_PROJ_EPL As String = "CurrProj.epl"
   Const CURR_PROJ_PPL As String = "CurrProj.ppl"

   ' OnProdLine
   Private Sub OnProdLine()
      ' Se richiesto aggiornamento diametro lama
      If m_CurrentMachine.nProdLiSawProbe >= 1 Then SawProbing(1)
      If m_CurrentMachine.nProdLiSawProbe >= 2 Then SawProbing(2)
      ' Se OmagVIEW non previsto, esco
      If String.IsNullOrWhiteSpace(m_CurrentMachine.sLineDataDir) OrElse
         Not My.Computer.FileSystem.DirectoryExists(m_CurrentMachine.sLineDataDir) Then Return
      ' Se modalità custom, gestione dell'evento lastra terminata
      If m_CurrentMachine.nSaveProduced = 3 Then
         ' Leggo variabile con indice progetto terminato (E81025 per Henraux)
         m_CNCommunication.m_CN.n_DReadELS_handle = 0
         m_CNCommunication.m_CN.ReadEls_Add_Parameter(m_CurrentMachine.sVarProjFinished, 1)
         Dim nVarFin As Integer = 0
         For I As Integer = 1 To 4
            System.Threading.Thread.Sleep(50)
            If m_CNCommunication.m_CN.n_DReadELS_handle = 1 Then
               nVarFin = CInt(m_CNCommunication.m_CN.d_DReadELS_value)
               Exit For
            End If
         Next
         ' Leggo variabile con ultimo progetto finito di lavorare
         Dim nLastFinished As Integer = GetPrivateProfileInt(S_GENERAL, K_LASTPROJFINISHED, 0, GetIniFile())
         ' Se nuovo progetto finito, ne salvo il tempo
         If nVarFin <> 0 And nVarFin <> nLastFinished Then
            ' Salvo in INI indice del progetto terminato
            WritePrivateProfileString(S_GENERAL, K_LASTPROJFINISHED, nVarFin.ToString("D4"), GetIniFile())
            ' Salvo in INI data e ora attuali di termine lavorazione del progetto (solo gli ultimi 10 tramite modulo)
            Dim sKey As String = K_DATETIMEFINISHED & "." & ( nVarFin Mod 10).ToString() 
            Dim sDateTime As String = My.Computer.Clock.LocalTime.ToString("dd.MM.yyyy HH\:mm\:ss")
            WritePrivateProfileString(S_GENERAL, sKey, sDateTime, GetIniFile())
            ' Eseguo script
            ExecFinishedProgScript( nVarFin, sDateTime)
         End If
      End If
      ' Se OmagVIEW blocca, esco (riproverò al prossimo giro)
      Dim sLockFile As String = m_CurrentMachine.sLineDataDir & "\" & CURR_PROJ_LOCK
      Dim sNewFile As String = m_CurrentMachine.sLineDataDir & "\" & CURR_PROJ_NEW
      If My.Computer.FileSystem.FileExists(sLockFile) OrElse
         My.Computer.FileSystem.FileExists(sNewFile) Then Return
      ' Verifico se richiesto cambio di progetto
      Dim nProjInd As Integer = 0
      Dim nMove As Integer = 0
      If ReadProjectChange(nProjInd, nMove) Then
         Dim nMaxProj As Integer = GetPrivateProfileInt(S_GENERAL, K_MAXPROJ, 100, GetIniFile())
         Dim nLastProj As Integer = GetPrivateProfileInt(S_GENERAL, K_LASTPROJTOVIEW, 0, GetIniFile())
         ' Se progetto valido, recupero il progetto del View
         If nProjInd > 0 Then
            ExecProjectUpdate(nProjInd)
            ' Se si vuole andare oltre ultimo, forzo ritrasmissione di questo
            If nProjInd = nLastProj And nMove = 1 Then
               nProjInd = If(nLastProj = 1, nMaxProj, nLastProj - 1)
               nMove = 1
            End If
            ' altrimenti forzo trasmissione ultimo inviato
         Else
            nProjInd = If(nLastProj = 1, nMaxProj, nLastProj - 1)
            nMove = 1
         End If
         ' Se richiesto cambio di progetto
         If nMove <> 0 Then
            ExecProjectChange(nProjInd, nMove)
            Return
         End If
      End If
      ' Se richieste modalità standard o speciali
      If m_CurrentMachine.nSaveProduced <> 3 Then
         StandardAndSpecialViewFileManagement()
      ' altrimenti modalità custom
      Else
         CustomViewFileManagement( nProjInd)
      End If
      ' Leggo variabile con indice progetto da copiare per OmagVIEW (standard E80025)
      m_CNCommunication.m_CN.n_DReadELS_handle = 0
      m_CNCommunication.m_CN.ReadEls_Add_Parameter(m_CurrentMachine.sVarProjCopy, 1)
      Dim nVarCopy As Integer = 0
      For I As Integer = 1 To 10
         System.Threading.Thread.Sleep(50)
         If m_CNCommunication.m_CN.n_DReadELS_handle = 1 Then
            nVarCopy = CInt(m_CNCommunication.m_CN.d_DReadELS_value)
            Exit For
         End If
      Next

      ' forzo la variabile CN - aggiornando il valore dell'indice del progetto in elaborazione
      If m_CurrentMachine.bDemo Then nVarCopy = GetPrivateProfileInt(S_GENERAL, K_LASTPROJ, 0, GetIniFile())

      ' Leggo variabile con ultimo progetto mandato a OmagView
      Dim nLastCopy As Integer = GetPrivateProfileInt(S_GENERAL, K_LASTPROJTOVIEW, 0, GetIniFile())
      ' Se non nulla e diversa da ultimo copiato, verifico se eseguire la copia
      If nVarCopy <> 0 And nVarCopy <> nLastCopy Then
         ' Verifico esistenza progetto con numerazione equivalente e assenza file di lock
         Dim sNgeFile As String = GetSaveDir() & "\" & nVarCopy.ToString("D4") & ".nge"
         Dim sEplFile As String = m_CurrentMachine.sLineDataDir & "\" & CURR_PROJ_EPL
         If My.Computer.FileSystem.FileExists(sNgeFile) And
            Not My.Computer.FileSystem.FileExists(sEplFile) Then
            Try
               ' Copio file di progetto nge
               Dim sNgeDest As String = m_CurrentMachine.sLineDataDir & "\" & CURR_PROJ_NGE
               My.Computer.FileSystem.CopyFile(sNgeFile, sNgeDest, True)
               ' Se esiste file jpg omonimo, lo copio
               Dim sJpgFile As String = System.IO.Path.ChangeExtension(sNgeFile, ".jpg")
               If My.Computer.FileSystem.FileExists(sJpgFile) Then
                  Dim sJpgDest As String = m_CurrentMachine.sLineDataDir & "\" & CURR_PROJ_JPG
                  My.Computer.FileSystem.CopyFile(sJpgFile, sJpgDest, True)
               End If
               ' Creo file per flag di nuovo progetto
               Dim NewWrt As New IO.StreamWriter(m_CurrentMachine.sLineDataDir & "\" & CURR_PROJ_NEW, False)
               NewWrt.WriteLine("Last")
               NewWrt.Close()
               ' Se non è scarico speciale (tipo Henraux), dichiaro progetto copiato azzerando la relativa variabile in macchina
               ' Con scarico speciale non va azzerata, perchè si incrementa con pulsante allo scarico
               If Not m_CurrentMachine.bSpecialUnload Then
                  m_CNCommunication.m_CN.DVariables_WriteVariables2(m_CurrentMachine.sVarProjCopy, "0")
               End If
               ' Salvo in INI indice del progetto copiato
               WritePrivateProfileString(S_GENERAL, K_LASTPROJTOVIEW, nVarCopy.ToString("D4"), GetIniFile())
               ' Salvo in INI data e ora attuali di inizio scarico
               WritePrivateProfileString(S_GENERAL, K_DATETIMETOVIEW, My.Computer.Clock.LocalTime.ToString("dd.MM.yyyy HH\:mm\:ss"), GetIniFile())
            Catch ex As Exception
               EgtOutLog("Error copying files to OmagVIEW")
               ' Errore in copia file per OmagVIEW
               m_CurrentProjectPageUC.SetErrorMessage(EgtMsg(91117))
            End Try
         End If
      End If
   End Sub

   Private Function SawProbing(nI As Integer) As Boolean
      ' Leggo da variabile CN se tastatura effettuata
      m_CNCommunication.m_CN.n_DReadELS_handle = 0
      m_CNCommunication.m_CN.ReadEls_Add_Parameter(m_CurrentMachine.sProdLiProbingStateVar(nI), 1)
      Dim nProbingState As Integer = 0
      For I As Integer = 1 To 5
         System.Threading.Thread.Sleep(20)
         If m_CNCommunication.m_CN.n_DReadELS_handle = 1 Then
            nProbingState = CInt(m_CNCommunication.m_CN.d_DReadELS_value)
            Exit For
         End If
      Next
      If nProbingState <> 1 Then Return False
      ' Leggo da variabile CN posizione lama in TC
      Dim nTcPos As Integer = 0
      If m_CurrentMachine.sProdLiProbingTcPosVar(nI) <> "0" Then
         m_CNCommunication.m_CN.n_DReadELS_handle = 0
         m_CNCommunication.m_CN.ReadEls_Add_Parameter(m_CurrentMachine.sProdLiProbingTcPosVar(nI), 1)
         For I As Integer = 1 To 5
            System.Threading.Thread.Sleep(20)
            If m_CNCommunication.m_CN.n_DReadELS_handle = 1 Then
               nTcPos = CInt(m_CNCommunication.m_CN.d_DReadELS_value)
               Exit For
            End If
         Next
      Else
         nTcPos = 100
      End If
      If nTcPos = 0 Then Return False
      ' Leggo da variabile CN nuovo diametro lama
      m_CNCommunication.m_CN.n_DReadELS_handle = 0
      m_CNCommunication.m_CN.ReadEls_Add_Parameter(m_CurrentMachine.sProdLiSawDiameterVar(nI), 1)
      Dim dDiam As Double = 0
      For I As Integer = 1 To 5
         System.Threading.Thread.Sleep(20)
         If m_CNCommunication.m_CN.n_DReadELS_handle = 1 Then
            dDiam = m_CNCommunication.m_CN.d_DReadELS_value
            Exit For
         End If
      Next
      If dDiam < EPS_SMALL Then Return False
      ' trasformo misura rilevata in mm
      If m_CNCommunication.GetMachineInInches() Then
         dDiam *= ONEINCH / 1000
      Else
         dDiam *= ONEMM / 1000
      End If
      ' Reset variabile CN di tastatura effettuata
      m_CNCommunication.m_CN.DVariables_WriteVariables2(m_CurrentMachine.sProdLiProbingStateVar(nI), "0")
      ' Aggiorno diametro lama
      Dim bFound As Boolean = False
      If nTcPos <> 100 Then
         Dim sTcPos As String = "T" & nTcPos.ToString()
         Dim sToolName As String = String.Empty
         Dim nType As Integer = MCH_TY.NONE
         Dim bNext As Boolean = EgtTdbGetFirstTool(MCH_TF.SAWBLADE, sToolName, nType)
         While bNext
            EgtTdbSetCurrTool(sToolName)
            Dim sToolTcPos As String = ""
            If EgtTdbGetCurrToolParam(MCH_TP.TCPOS, sToolTcPos) AndAlso sTcPos = sToolTcPos Then
               bFound = True
               Exit While
            End If
            bNext = EgtTdbGetNextTool(MCH_TF.SAWBLADE, sToolName, nType)
         End While
      Else
         Dim sToolName As String = m_CurrentMachine.sCurrSaw
         If nI = 2 Then
            sToolName &= "-2"
         End If
         EgtTdbSetCurrTool(sToolName)
         bFound = True
      End If
      If Not bFound Then Return False
      EgtTdbSetCurrToolParam(MCH_TP.DIAM, dDiam)
      EgtTdbSetCurrToolParam(MCH_TP.TOTDIAM, dDiam)
      EgtTdbSaveCurrTool()
      EgtTdbSave()
      Return True
   End Function

   Private Function ReadProjectChange(ByRef nProjInd As Integer, ByRef nMove As Integer) As Boolean
      ' Verifico presenza file di richiesta
      Dim sChangeFile As String = m_CurrentMachine.sLineDataDir & "\" & CURR_PROJ_CHANGE
      If Not My.Computer.FileSystem.FileExists(sChangeFile) Then Return False
      ' Leggo i dati dal file
      Try
         Dim ChangeRdr As New IO.StreamReader(sChangeFile)
         Dim sProjInd As String = ChangeRdr.ReadLine()
         Dim sMove As String = ChangeRdr.ReadLine()
         ChangeRdr.Close()
         If Not Int32.TryParse(GetValueWithKey(sProjInd, "Proj"), nProjInd) Then nProjInd = 0
         If Not Int32.TryParse(GetValueWithKey(sMove, "Move"), nMove) Then nMove = 0
         Return True
      Catch
         Return False
      Finally
         ' Rimuovo segnalazione di cambio progetto
         Try
            My.Computer.FileSystem.DeleteFile(sChangeFile)
         Catch
         End Try
      End Try
   End Function

   Private Function ExecProjectUpdate(nProjInd As Integer) As Boolean
      Dim sSouFile As String = m_CurrentMachine.sLineDataDir & "\" & CURR_PROJ_NGE
      Dim sDestFile As String = GetSaveDir() & "\" & nProjInd.ToString("D4") & ".nge"
      Try
         My.Computer.FileSystem.CopyFile(sSouFile, sDestFile, True)
         Return True
      Catch
         Return False
      End Try
   End Function

   Private Function ExecProjectChange(nProjInd As Integer, nMove As Integer) As Boolean
      ' Massimo indice di un progetto
      Dim nMaxProj As Integer = GetPrivateProfileInt(S_GENERAL, K_MAXPROJ, 100, GetIniFile())
      ' Progetto corrente
      Dim nCurrProj As Integer = GetPrivateProfileInt(S_GENERAL, K_LASTPROJ, 0, GetIniFile())
      ' Ultimo progetto inviato al View automaticamente
      Dim nLastProj As Integer = GetPrivateProfileInt(S_GENERAL, K_LASTPROJTOVIEW, 0, GetIniFile())
      ' File da inviare
      Dim nNewProjInd As Integer = 0
      Dim sNewFile As String = ""
      ' Se richiesto progetto precedente
      If nMove < 0 Then
         nNewProjInd = nProjInd - 1
         ' Retrocedendo non posso arrivare all'ultimo progetto
         If nNewProjInd = nCurrProj Or nNewProjInd = nLastProj Then nNewProjInd = nProjInd
         While nNewProjInd > 0
            Dim sFile As String = GetSaveDir() & "\" & nNewProjInd.ToString("D4") & ".nge"
            If My.Computer.FileSystem.FileExists(sFile) Then
               sNewFile = sFile
               Exit While
            End If
            nNewProjInd -= 1
         End While
         If nNewProjInd = 0 Then
            nNewProjInd = nMaxProj
            While nNewProjInd > nCurrProj
               Dim sFile As String = GetSaveDir() & "\" & nNewProjInd.ToString("D4") & ".nge"
               If My.Computer.FileSystem.FileExists(sFile) Then
                  sNewFile = sFile
                  Exit While
               End If
               nNewProjInd -= 1
            End While
         End If
      ' se altrimenti richiesto progetto successivo
      ElseIf nMove > 0 Then
         nNewProjInd = nProjInd + 1
         If nProjInd > nLastProj Then
            While nNewProjInd <= nMaxProj
               Dim sFile As String = GetSaveDir() & "\" & nNewProjInd.ToString("D4") & ".nge"
               If My.Computer.FileSystem.FileExists(sFile) Then
                  sNewFile = sFile
                  Exit While
               End If
               nNewProjInd += 1
            End While
            If nNewProjInd > nMaxProj Then nNewProjInd = 1
         End If
         While nNewProjInd <= nLastProj
            Dim sFile As String = GetSaveDir() & "\" & nNewProjInd.ToString("D4") & ".nge"
            If My.Computer.FileSystem.FileExists(sFile) Then
               sNewFile = sFile
               Exit While
            End If
            nNewProjInd += 1
         End While
      End If
      ' Se non trovato progetto da inviare
      If String.IsNullOrWhiteSpace(sNewFile) Then Return False
      ' Copio il progetto
      Try
         ' Copio file di progetto nge
         Dim sNgeDest As String = m_CurrentMachine.sLineDataDir & "\" & CURR_PROJ_NGE
         My.Computer.FileSystem.CopyFile(sNewFile, sNgeDest, True)
         ' Se esiste file jpg omonimo, lo copio
         Dim sJpgFile As String = System.IO.Path.ChangeExtension(sNewFile, ".jpg")
         If My.Computer.FileSystem.FileExists(sJpgFile) Then
            Dim sJpgDest As String = m_CurrentMachine.sLineDataDir & "\" & CURR_PROJ_JPG
            My.Computer.FileSystem.CopyFile(sJpgFile, sJpgDest, True)
         End If
         ' Creo file per flag di nuovo progetto
         Dim NewWrt As New IO.StreamWriter(m_CurrentMachine.sLineDataDir & "\" & CURR_PROJ_NEW, False)
         NewWrt.WriteLine(If(nNewProjInd = nLastProj, "Last", "Status"))
         NewWrt.Close()
      Catch ex As Exception
         EgtOutLog("Error change copying files to OmagVIEW")
         ' Errore in copia file per OmagVIEW
         m_CurrentProjectPageUC.SetErrorMessage(EgtMsg(91117))
      End Try
      Return True
   End Function

   Private Function StandardAndSpecialViewFileManagement() As Boolean
      ' Acquisizione eventuale file epl dei pezzi rovinati :
      '   lo sposto dal direttorio condiviso al direttorio dei rovinati e poi lo fondo in quello generale
      Dim sSouEplFile As String = m_CurrentMachine.sLineDataDir & "\" & CURR_PROJ_EPL
      If My.Computer.FileSystem.FileExists(sSouEplFile) Then
         ' Flag gestione unico file dei rovinati
         Dim bSingleFile As Boolean = True
         ' Se gestione pezzi e rovinati prodotti
         If m_CurrentMachine.nSaveProduced <> 0 Then
            ' Recupero path di origine del relativo file OmagCUT
            Dim sCutDir As String = GetCutOrigDir(sSouEplFile)
            ' Se questo direttorio esiste
            bSingleFile = Not My.Computer.FileSystem.DirectoryExists(sCutDir)
         End If
         ' Se gestione pezzi rovinati con un unico file
         If bSingleFile Then
            Dim sRuPartsDir As String = GetRuinedPartsDir()
            Dim sDestEplFile = sRuPartsDir & "\" & CURR_PROJ_EPL
            ' Eseguo spostamento file
            Try
               My.Computer.FileSystem.MoveFile(sSouEplFile, sDestEplFile, True)
            Catch ex As Exception
               EgtOutLog("Error moving or erasing " & sSouEplFile)
            End Try
            ' Path del file generale dei rovinati
            Dim sRuinedFile As String = sRuPartsDir & "\" & CURR_RUINED_EPL
            ' Path della lista caricata per edit
            Dim sCurrCsvFile As String = String.Empty
            GetPrivateProfileString(S_CSV, K_CSVLASTFILE, "", sCurrCsvFile, m_sIniFile)
            ' Se lista corrente è quella dei pezzi rovinati, la salvo
            If String.Compare(sCurrCsvFile, sRuinedFile, True) = 0 Then
               m_CadCutPageUC.m_CSVPage.SaveCsvPartList()
            End If
            ' Leggo file generale dei rovinati
            Dim sDummy As String = String.Empty
            Dim CsvPartList As New List(Of CsvPart)
            ReadCsvPartList(sRuinedFile, sDummy, CsvPartList)
            ' Accodo eventuali nuovi pezzi rovinati leggendo dal file particolare
            ReadCsvPartList(sDestEplFile, sDummy, CsvPartList)
            ' Elimino pezzi non più da nestare
            RemoveNotToNestParts(CsvPartList)
            ' Scrivo file generale dei rovinati 
            WriteCsvPartList(sRuinedFile, sRuinedFile, CsvPartList)
            ' Se lista corrente è quella dei rovinati, la rileggo
            If String.Compare(sCurrCsvFile, sRuinedFile, True) = 0 Then
               m_CadCutPageUC.m_CSVPage.UpdateCsvPartList()
            End If
            ' Cancello file particolare dei rovinati
            Try
               My.Computer.FileSystem.DeleteFile(sDestEplFile)
            Catch ex As Exception
               EgtOutLog("Error erasing " & sDestEplFile)
            End Try
         ' altrimenti, ogni commessa ha il suo file dei pezzi rovinati
         Else
            ' Sposto nel direttorio temporaneo
            Dim sDestEplFile = m_sTempDir & "\" & CURR_PROJ_EPL
            Try
               My.Computer.FileSystem.MoveFile(sSouEplFile, sDestEplFile, True)
            Catch ex As Exception
               EgtOutLog("Error moving or erasing " & sSouEplFile)
            End Try
            ' Recupero direttorio di origine del relativo file OmagCUT
            Dim sCutDir As String = GetCutOrigDir(sDestEplFile)
            ' Path del file generale dei pezzi rovinati
            Const CURR_RUINED_EPL As String = "Ruined.epl"
            Dim sRuinFile As String = sCutDir & "\" & CURR_RUINED_EPL
            ' Path della lista caricata per edit
            Dim sCurrCsvFile As String = String.Empty
            GetPrivateProfileString(S_CSV, K_CSVLASTFILE, "", sCurrCsvFile, m_sIniFile)
            ' Se lista corrente è quella dei rovinati, la salvo
            If String.Compare(sCurrCsvFile, sRuinFile, True) = 0 Then
               m_CadCutPageUC.m_CSVPage.SaveCsvPartList()
            End If
            ' Leggo file generale dei pezzi rovinati
            Dim sDummy As String = String.Empty
            Dim CsvPartList As New List(Of CsvPart)
            ReadCsvPartList(sRuinFile, sDummy, CsvPartList)
            ' Accodo eventuali nuovi pezzi rovinati leggendo dal file particolare
            ReadCsvPartList(sDestEplFile, sDummy, CsvPartList)
            ' Elimino pezzi non più da nestare
            RemoveNotToNestParts(CsvPartList)
            ' Scrivo file generale dei rovinati
            WriteCsvPartList(sRuinFile, sRuinFile, CsvPartList)
            ' Se lista corrente è quella dei rovinati, la rileggo
            If String.Compare(sCurrCsvFile, sRuinFile, True) = 0 Then
               m_CadCutPageUC.m_CSVPage.UpdateCsvPartList()
            End If
            ' Cancello file particolare dei rovinati
            Try
               My.Computer.FileSystem.DeleteFile(sDestEplFile)
            Catch ex As Exception
               EgtOutLog("Error erasing " & sDestEplFile)
            End Try
         End If
      End If
      ' Se richiesto, acquisizione eventuale file ppl dei pezzi prodotti :
      '   lo sposto dal direttorio condiviso al direttorio temporaneo, per poi fonderlo nello specifico dei prodotti
      Dim sSouPplFile As String = m_CurrentMachine.sLineDataDir & "\" & CURR_PROJ_PPL
      If m_CurrentMachine.nSaveProduced <> 0 AndAlso My.Computer.FileSystem.FileExists(sSouPplFile) Then
         ' Sposto nel direttorio temporaneo
         Dim sDestPplFile = m_sTempDir & "\" & CURR_PROJ_PPL
         Try
            My.Computer.FileSystem.MoveFile(sSouPplFile, sDestPplFile, True)
         Catch ex As Exception
            EgtOutLog("Error moving or erasing " & sSouPplFile)
         End Try
         ' Definizione direttorio e nome file di destinazione a seconda della modalità 
         Dim sDestDir As String = String.Empty
         Dim sDestFile As String = String.Empty
         If m_CurrentMachine.nSaveProduced = 1 Then
            ' Recupero path di origine del relativo file OmagCUT
            sDestDir = GetCutOrigDir(sDestPplFile)
            sDestFile = "Produced.epl"
         Else
            If GetPrivateProfileString(S_CSV, K_PRODUCEDPARTSDIR, "", sDestDir, m_sIniFile) = 0 Then
               sDestDir = m_sDataRoot & "\" & PRODUCEDPARTS_DFL_DIR
            End If
            sDestFile = System.DateTime.Now.ToString("yyyy_MM_dd") & ".epl"
         End If
         ' Se questo direttorio esiste
         If My.Computer.FileSystem.DirectoryExists(sDestDir) Then
            ' Path del file generale dei pezzi prodotti
            Dim sProdFile As String = sDestDir & "\" & sDestFile
            ' Path della lista caricata per edit
            Dim sCurrCsvFile As String = String.Empty
            GetPrivateProfileString(S_CSV, K_CSVLASTFILE, "", sCurrCsvFile, m_sIniFile)
            ' Se lista corrente è quella dei pezzi, la salvo
            If String.Compare(sCurrCsvFile, sProdFile, True) = 0 Then
               m_CadCutPageUC.m_CSVPage.SaveCsvPartList()
            End If
            ' Leggo file generale dei pezzi prodotti
            Dim sDummy As String = String.Empty
            Dim CsvPartList As New List(Of CsvPart)
            ReadCsvPartList(sProdFile, sDummy, CsvPartList)
            ' Accodo eventuali nuovi pezzi prodotti leggendo dal file particolare
            ReadCsvPartList(sDestPplFile, sDummy, CsvPartList)
            ' Scrivo file generale dei prodotti
            WriteCsvPartList(sProdFile, sProdFile, CsvPartList)
            ' Se lista corrente è quella dei prodotti, la rileggo
            If String.Compare(sCurrCsvFile, sProdFile, True) = 0 Then
               m_CadCutPageUC.m_CSVPage.UpdateCsvPartList()
            End If
            ' Cancello file particolare dei prodotti
            Try
               My.Computer.FileSystem.DeleteFile(sDestPplFile)
            Catch ex As Exception
               EgtOutLog("Error erasing " & sDestPplFile)
            End Try
         Else
            Dim sProdPartsDir As String = String.Empty
            If GetPrivateProfileString(S_CSV, K_PRODUCEDPARTSDIR, "", sProdPartsDir, m_sIniFile) = 0 OrElse
               Not My.Computer.FileSystem.DirectoryExists(sProdPartsDir) Then
               sProdPartsDir = m_sDataRoot & "\" & PRODUCEDPARTS_DFL_DIR
            End If
            Dim sTmpPplFile = sProdPartsDir & "\" & System.DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") & ".epl"
            My.Computer.FileSystem.MoveFile(sDestPplFile, sTmpPplFile, True)
            EgtOutLog("Error with " & sDestDir)
         End If
      End If
      Return True
   End Function

   Private Function CustomViewFileManagement( nProjInd As Integer) As Boolean
      ' Se non esiste file EPL, esco
      Dim sSouEplFile As String = m_CurrentMachine.sLineDataDir & "\" & CURR_PROJ_EPL
      If Not My.Computer.FileSystem.FileExists(sSouEplFile) Then Return True
      ' Se non esiste file PPL, esco
      Dim sSouPplFile As String = m_CurrentMachine.sLineDataDir & "\" & CURR_PROJ_PPL
      If Not My.Computer.FileSystem.FileExists(sSouPplFile) Then Return True
      ' Se non esiste file NGE, esco
      Dim sSouNgeFile As String = m_CurrentMachine.sLineDataDir & "\" & CURR_PROJ_NGE
      If Not My.Computer.FileSystem.FileExists(sSouNgeFile) Then Return True
      ' Sposto file epl dei pezzi rovinati nel direttorio temporaneo
      Dim sDestEplFile = m_sTempDir & "\" & CURR_PROJ_EPL
      Try
         My.Computer.FileSystem.MoveFile(sSouEplFile, sDestEplFile, True)
      Catch ex As Exception
         EgtOutLog("Error moving or erasing " & sSouEplFile)
      End Try
      ' Sposto file ppl dei pezzi prodotti nel direttorio temporaneo
      Dim sDestPplFile = m_sTempDir & "\" & CURR_PROJ_PPL
      Try
         My.Computer.FileSystem.MoveFile(sSouPplFile, sDestPplFile, True)
      Catch ex As Exception
         EgtOutLog("Error moving or erasing " & sSouPplFile)
      End Try
      ' Sposto file nge dei pezzi prodotti nel direttorio temporaneo
      Dim sDestNgeFile = m_sTempDir & "\" & CURR_PROJ_NGE
      Try
         My.Computer.FileSystem.MoveFile(sSouNgeFile, sDestNgeFile, True)
      Catch ex As Exception
         EgtOutLog("Error moving or erasing " & sSouNgeFile)
      End Try
      ' Leggo variabile con ultimo progetto mandato a OmagView
      Dim nLastCopy As Integer = GetPrivateProfileInt(S_GENERAL, K_LASTPROJTOVIEW, 0, GetIniFile())
      ' Leggo variabile con data inizio scarico
      Dim sDateTime As String = String.Empty
      GetPrivateProfileString(S_GENERAL, K_DATETIMETOVIEW, "", sDateTime, GetIniFile())
      ' Verifico progetto restituito da View
      If nProjInd = 0 Then nProjInd = nLastCopy
      ' Leggo variabile con data termine lavorazione
      Dim sKey As String = K_DATETIMEFINISHED & "." & ( nProjInd Mod 10).ToString() 
      GetPrivateProfileString(S_GENERAL, sKey, sDateTime, sDateTime, GetIniFile())
      ' Recupero direttorio per pezzi rovinati
      Dim sRuPartsDir As String = GetRuinedPartsDir()
      ' Esecuzione dello script custom
      ExecReceivedViewScript(nProjInd, sDateTime, sRuPartsDir)
      ' Cancello file dei pezzi rovinati
      Try
         My.Computer.FileSystem.DeleteFile(sDestEplFile)
      Catch ex As Exception
         EgtOutLog("Error erasing " & sDestEplFile)
      End Try
      ' Cancello file dei pezzi prodotti
      Try
         My.Computer.FileSystem.DeleteFile(sDestPplFile)
      Catch ex As Exception
         EgtOutLog("Error erasing " & sDestPplFile)
      End Try
      ' Cancello file con le geometrie dei pezzi
      Try
         My.Computer.FileSystem.DeleteFile(sDestNgeFile)
      Catch ex As Exception
         EgtOutLog("Error erasing " & sDestNgeFile)
      End Try
      Return True
   End Function

   Friend Function ExecSentProgScript( bDirectCut As Boolean, Optional bAlreadySent As Boolean = False) As Boolean
      ' Verifico esistenza script
      Dim sLuaPath As String = m_CurrentMachine.sMachDir() & "\Scripts\SentProg.lua"
      If Not My.Computer.FileSystem.FileExists(sLuaPath) Then Return True
      ' Definizione variabili
      EgtLuaCreateGlobTable("SPS")
      EgtLuaSetGlobBoolVar("SPS.NCLINK", m_bNCLink)
      EgtLuaSetGlobBoolVar("SPS.PRODLINE", m_CurrentMachine.bProdLine)
      EgtLuaSetGlobBoolVar("SPS.ALREADYSENT", bAlreadySent)
      EgtLuaSetGlobBoolVar("SPS.DIRECTCUT", bDirectCut)
      ' Esecuzione
      Dim nErr As Integer = 999
      If EgtLuaExecFile(sLuaPath) AndAlso
         EgtLuaCallFunction("SPS.Exec") Then
         ' Verifica stato di errore
         EgtLuaGetGlobIntVar("SPS.ERR", nErr)
      End If
      EgtLuaResetGlobVar("SPS")
      If nErr <> 0 Then
          EgtOutLog("Error in SentProg : " & nErr.ToString())
          m_CurrentProjectPageUC.SetErrorMessage(EgtMsg(90325))       'Errore nel salvataggio delle statistiche
      End If
      Return (nErr = 0)
   End Function

   Private Function ExecFinishedProgScript(nProjInd As Integer, sDateTime As String) As Boolean
      ' Verifico esistenza script
      Dim sLuaPath As String = m_CurrentMachine.sMachDir() & "\Scripts\FinishedProg.lua"
      If Not My.Computer.FileSystem.FileExists(sLuaPath) Then Return True
      ' Definizione variabili
      EgtLuaCreateGlobTable("FPS")
      EgtLuaSetGlobBoolVar("FPS.NCLINK", m_bNCLink)
      EgtLuaSetGlobBoolVar("FPS.PRODLINE", m_CurrentMachine.bProdLine)
      EgtLuaSetGlobStringVar("FPS.LASTCOPY", nProjInd.ToString("D4"))
      EgtLuaSetGlobStringVar("FPS.DATETIME", sDateTime)
      EgtLuaSetGlobIntVar("FPS.RUPARTSCNT", 0)
      ' Esecuzione
      Dim nErr As Integer = 999
      Dim nRuPartsCnt As Integer = 0
      If EgtLuaExecFile(sLuaPath) AndAlso
         EgtLuaCallFunction("FPS.Exec") Then
         ' Verifica stato di errore
         EgtLuaGetGlobIntVar("FPS.ERR", nErr)
      End If
      EgtLuaResetGlobVar("FPS")
      ' Contesto Scena del Progetto
      Dim nCurrCtx As Integer = EgtGetCurrentContext()
      EgtSetCurrentContext(m_CurrentProjectPageUC.CurrentProjectScene.GetCtx())
      If nErr <> 0 Then
         EgtOutLog("Error in FinishedProg : " & nErr.ToString())
         m_CurrentProjectPageUC.SetErrorMessage(EgtMsg(90325))       'Errore nel salvataggio delle statistiche
      End If
      ' Ripristino contesto originale
      EgtSetCurrentContext(nCurrCtx)
      Return (nErr = 0)
   End Function

   Private Function ExecReceivedViewScript(nProjInd As Integer, sDateTime As String, sRuPartsDir As String) As Boolean
      ' Verifico esistenza script
      Dim sLuaPath As String = m_CurrentMachine.sMachDir() & "\Scripts\ReceivedView.lua"
      If Not My.Computer.FileSystem.FileExists(sLuaPath) Then Return True
      ' Definizione variabili
      EgtLuaCreateGlobTable("RVS")
      EgtLuaSetGlobBoolVar("RVS.NCLINK", m_bNCLink)
      EgtLuaSetGlobBoolVar("RVS.PRODLINE", m_CurrentMachine.bProdLine)
      EgtLuaSetGlobStringVar("RVS.LASTCOPY", nProjInd.ToString("D4"))
      EgtLuaSetGlobStringVar("RVS.DATETIME", sDateTime)
      EgtLuaSetGlobStringVar("RVS.RUPARTSDIR", sRuPartsDir)
      EgtLuaSetGlobIntVar("RVS.RUPARTSCNT", 0)
      ' Esecuzione
      Dim nErr As Integer = 999
      Dim nRuPartsCnt As Integer = 0
      If EgtLuaExecFile(sLuaPath) AndAlso
         EgtLuaCallFunction("RVS.Exec") Then
         ' Verifica stato di errore
         EgtLuaGetGlobIntVar("RVS.ERR", nErr)
         ' Lettura numero pezzi rovinati eventualmente inseriti
         EgtLuaGetGlobIntVar("RVS.RUPARTSCNT", nRuPartsCnt)
      End If
      EgtLuaResetGlobVar("RVS")
      ' Contesto Scena del Progetto
      Dim nCurrCtx As Integer = EgtGetCurrentContext()
      EgtSetCurrentContext(m_CurrentProjectPageUC.CurrentProjectScene.GetCtx())
      If nErr <> 0 Then
         EgtOutLog("Error in ReceivedView : " & nErr.ToString())
         m_CurrentProjectPageUC.SetErrorMessage(EgtMsg(90325))       'Errore nel salvataggio delle statistiche
      ElseIf nRuPartsCnt > 0 Then
         EgtOutLog("New Ruined Parts : " & nRuPartsCnt.ToString())
         m_CurrentProjectPageUC.SetInfoMessage(EgtMsg(90327))        'Inseriti Nuovi Pezzi Rovinati
         Dim nPartId As Integer = EgtGetLastPart()
         For nI As Integer = 1 To nRuPartsCnt
            EgtRemoveInfo( nPartId, INFO_PARTOK)
            m_CadCutPageUC.m_NestPage.StoreOnePart(nPartId, True)
            nPartId = EgtGetPrevPart(nPartId)
         Next
         ' Visualizzazione
         EgtZoom(ZM.ALL)
      End If
      ' Dichiaro progetto passato da View
      If nProjInd = m_CurrentProjectPageUC.GetCurrentProject() Then
         EgtSetInfo( EgtGetFirstNameInGroup(GDB_ID.ROOT, NAME_PROJMARK), INFO_UNLOADSAVED, 1)
      Else
         Dim nTmpCtx As Integer = EgtInitContext()
         If nTmpCtx <> 0 Then
            Dim sNgeFile As String = GetSaveDir() & "\" & nProjInd.ToString("D4") & ".nge"
            EgtOpenFile( sNgeFile)
            EgtSetInfo( EgtGetFirstNameInGroup(GDB_ID.ROOT, NAME_PROJMARK), INFO_UNLOADSAVED, 1)
            EgtSaveFile( sNgeFile, NGE.CMPTEXT)
            EgtDeleteContext( nTmpCtx)
            EgtSetCurrentContext(m_CurrentProjectPageUC.CurrentProjectScene.GetCtx())
         End If
      End If
      ' Aggiorno Area da lavorare dei pezzi
      m_CurrentProjectPageUC.UpdateToProduceArea()
      m_CurrentProjectPageUC.ShowAreas()
      m_CurrentProjectPageUC.SaveProject()
      EgtDraw()
      ' Ripristino contesto originale
      EgtSetCurrentContext(nCurrCtx)
      Return (nErr = 0)
   End Function

   Private Function GetCutOrigDir(sPplFile As String) As String
      ' Recupero path di origine del relativo file OmagCUT
      Dim sCutPath As String = String.Empty
      GetPrivateProfileString("General", "Path", "", sCutPath, sPplFile)
      ' Ne ricavo direttorio di origine o il padre se si chiama MACCHINA
      Dim sCutDir As String
      Try
         sCutDir = Path.GetDirectoryName(sCutPath)
         If Path.GetFileName(sCutDir).ToUpper() = "MACCHINA" Then
            sCutDir = Path.GetDirectoryName(sCutDir)
         End If
      Catch ex As Exception
         sCutDir = ""
      End Try
      Return sCutDir
   End Function

   ' Evento che apre AboutBox quando viene clickato il logo
   Private Sub LogoBrd_MouseDown(sender As Object, e As MouseButtonEventArgs) Handles LogoBrd.MouseDown
      ' Se non premuto Shift -> AboutBox
      If ( Keyboard.Modifiers And ModifierKeys.Shift) = 0 Then  
         Dim AboutBox As New AboutBoxWD( Me)
      ' Altrimenti lancio cambio macchina (solo uso interno)
      Else
         If m_ActivePage = Pages.CadCut Or m_ActivePage = Pages.FrameCut Then
            ' Cambio macchina
            EgtLuaCreateGlobTable( "CHM")
            EgtLuaExecFile( GetConfigDir() & "\ChangeMachine.lua")
            Dim nRestart As Integer = 0
            EgtLuaGetGlobIntVar( "CHM.RESTART", nRestart)
            EgtLuaResetGlobVar( "CHM")
            ' Riavvio
            If nRestart = 1 Then
               Close()
               Process.Start( Application.ResourceAssembly.Location)
            End If
         End If
      End If
   End Sub

   ' Funzione che disabilita tutte le scene
   Private Sub IsEnabledScenes(IsEnabled As Boolean)
      If Not IsNothing(m_CurrentProjectPageUC.CurrentProjectScene) Then m_CurrentProjectPageUC.CurrentProjectScene.Enabled = IsEnabled
      If Not IsNothing(m_MachinePageUC.m_ToolsDbPageUC) Then m_MachinePageUC.m_ToolsDbPageUC.ToolScene.Enabled = IsEnabled
      If Not IsNothing(m_WorkInProgressPageUC) Then m_WorkInProgressPageUC.WorkInProgressScene.Enabled = IsEnabled
      If Not IsNothing(m_OpenPage) Then m_OpenPage.OpenScene.Enabled = IsEnabled
      If Not IsNothing(m_DrawPageUC) Then m_DrawPageUC.DrawScene.Enabled = IsEnabled
      If Not IsNothing(ProjectMgrUC.m_VeinMatchingWnd) Then ProjectMgrUC.m_VeinMatchingWnd.IsEnabled = IsEnabled
   End Sub

   ' spegne gli oggetti selezionati in fase di Check-Up-Start (bottone Test)
   Public Sub TestOff()
      ' deseleziono gli oggetti e spengo il bottone
      EgtDeselectObj(m_CadCutPageUC.m_NestPage.m_CurrSelectedCurv)
      EgtDeselectObj(m_CadCutPageUC.m_NestPage.m_CurrSelectedSawCurv)
      EgtResetMark(m_CadCutPageUC.m_NestPage.m_CurrSelectedSawCurv)
      m_CadCutPageUC.m_ProjectMgr.TestBtn.IsChecked = False
      Me.m_CadCutPageUC.m_NestPage.m_bSelectCurv = False
   End Sub

   ' spegne il comando per la mofica dei rettangoli
   Public Sub DragRettangleOff()
      m_CadCutPageUC.m_NestPage.DragRettanleBtn.IsChecked = False
      Me.m_CadCutPageUC.m_NestPage.m_bIsCheckedDragRettangle = False
      ShowParkedParts()

   End Sub

End Class