Files
cameramanager/CameraMng/SetConfigForm.vb
T
2025-07-30 16:56:29 +02:00

386 lines
17 KiB
VB.net

Imports System.Globalization
Imports System.IO
Public Class SetConfigForm
Private CameraListCfg As New List(Of String)
Private myImage As Image
Private CurrIndexRow As Integer = 0
Private CurrAppliedConfig As String = 0
Private bIsSavedAll As Boolean = True
Private IDConfig As String = String.Empty
Private IDCamera As String = String.Empty
Private IndexCurrentRow As Integer = 0
Sub New()
' La chiamata è richiesta dalla finestra di progettazione.
InitializeComponent()
' Aggiungere le eventuali istruzioni di inizializzazione dopo la chiamata a InitializeComponent().
End Sub
Private Sub LoadWindows() Handles Me.Load
PopolateDataGrid()
CurrAppliedConfig = If(FrmMain.ComboBoxCameraCfg.SelectedItem.Equals("Default"), "0", FrmMain.ComboBoxCameraCfg.SelectedItem)
' Deseleziona tutte le righe attualmente selezionate (opzionale ma consigliato)
DataGridView1.ClearSelection()
' Verifica che la griglia non sia vuota
If DataGridView1.Rows.Count > 0 Then
' Imposta la cella corrente alla prima cella della prima riga
DataGridView1.CurrentCell = DataGridView1.Rows(CurrAppliedConfig).Cells(0)
DataGridView1.Rows(CurrAppliedConfig).Selected = True
End If
End Sub
Private Sub PopolateDataGrid()
DataGridView1.Rows.Clear()
CameraListCfg.Clear()
ComboCamera.Items.Clear()
Dim DirToReadCfg As String = FrmMain.sDataRoot
' Popolo combobox con idcamera
For Each CameraItem As String In FrmMain.ComboBoxCameras.Items
ComboCamera.Items.Add(CameraItem)
Next
' Popolo text con configurazione
For Each CfgItem As String In FrmMain.ComboBoxCameraCfg.Items
Dim NomeFileCfg As String = DirToReadCfg & If(CfgItem = "Default", String.Empty, CfgItem) & "\CameraMng.cfg"
Dim riga As New DataGridViewRow()
' Crea le celle corrispondenti alle colonne
riga.CreateCells(DataGridView1)
riga.Cells(0).Value = CfgItem
Dim id As String = ReadIdCameraFromCfg(NomeFileCfg)
If Not String.IsNullOrEmpty(id) Then
' Icone CFG
If CameraListCfg.IndexOf(id) < 0 Then
CameraListCfg.Add(id)
riga.Cells(1).Value = GetCurrIco(2)
Else
riga.Cells(1).Value = GetCurrIco(0)
End If
' Icone CAMERA
If ComboCamera.Items.IndexOf(id) > -1 Then
riga.Cells(3).Value = GetCurrIco(2)
riga.Cells(2).Value = id
Else
riga.Cells(3).Value = GetCurrIco(0)
End If
Else
riga.Cells(1).Value = GetCurrIco(-1)
riga.Cells(3).Value = GetCurrIco(-1)
End If
riga.Cells(4).Value = "Save"
riga.Cells(5).Value = "Apply"
' Aggiungi la riga completa al DataGridView
DataGridView1.Rows.Add(riga)
If CfgItem = FrmMain.ComboBoxCameraCfg.SelectedItem Then
DataGridView1.ClearSelection()
' Mantengo la selezione sulla riga corrente
DataGridView1.Rows(DataGridView1.Rows.Count - 1).Selected = True
' Indico in grassetto il comando Apply
' Mi assicuro che la cella sia del tipo corretto
If TypeOf riga.Cells(5) Is DataGridViewButtonCell Then
' Ottiengo la cella specifica
Dim cellaBottone As DataGridViewButtonCell = CType(riga.Cells(5), DataGridViewButtonCell)
' Recupero il font attuale della cella per non perdere le altre proprietà (come la dimensione)
Dim fontAttuale As Font = cellaBottone.Style.Font
' Se non è stato impostato un font, usane uno di default per sicurezza
If fontAttuale Is Nothing Then
fontAttuale = Me.DataGridView1.Font ' Usa il font del DataGridView come base
End If
' Assegno un NUOVO oggetto Font con lo stile Bold
cellaBottone.Style.Font = New Font(fontAttuale, FontStyle.Bold)
End If
End If
Next
End Sub
Private Sub RefreshDataGrid(IndexRawDataGrid As Integer)
DataGridView1.ClearSelection()
Dim CfgItem As String = DataGridView1.Rows(IndexRawDataGrid).Cells("Config").Value.ToString()
' Aggiorno lo stato delle icone della lista
Dim DirToReadCfg As String = FrmMain.sDataRoot
Dim NomeFileCfg As String = DirToReadCfg & If(CfgItem = "Default", String.Empty, CfgItem) & "\CameraMng.cfg"
' Creo la nuova riga che sostituirà quella precedente
Dim riga As DataGridViewRow = DataGridView1.Rows(IndexRawDataGrid)
' Crea le celle corrispondenti alle colonne
riga.Cells(0).Value = CfgItem
Dim id As String = ReadIdCameraFromCfg(NomeFileCfg)
If Not String.IsNullOrEmpty(id) Then
' Icone CFG
If CameraListCfg.IndexOf(id) < 0 Then
riga.Cells(1).Value = GetCurrIco(2)
Else
riga.Cells(1).Value = GetCurrIco(0)
End If
' Icone CAMERA
If ComboCamera.Items.IndexOf(id) > -1 Then
riga.Cells(3).Value = GetCurrIco(2)
riga.Cells(2).Value = id
Else
riga.Cells(3).Value = GetCurrIco(0)
End If
Else
riga.Cells(1).Value = GetCurrIco(-1)
riga.Cells(3).Value = GetCurrIco(-1)
End If
riga.Cells(4).Value = "Save"
riga.Cells(5).Value = "Apply"
' Sostituisco la riga corrente: rimuovo la precedente riga e ne inserisco una nuova
DataGridView1.Rows.RemoveAt(IndexRawDataGrid)
DataGridView1.Rows.Insert(IndexRawDataGrid, riga)
' Mantengo la selezione sulla riga corrente
DataGridView1.CurrentCell = riga.Cells(0)
DataGridView1.Rows(IndexRawDataGrid).Selected = True
End Sub
Private Sub RefreshSelectedItemCfg(IndexRawDataGrid As Integer)
' 1. RIPRISTINA IL FONT DELLA RIGA PRECEDENTE
' Controlla se c'era una riga precedente valida e se non è la stessa che stiamo per modificare
If CurrAppliedConfig > -1 AndAlso CurrAppliedConfig <> IndexRawDataGrid Then
' Assicurati che l'indice sia ancora nel range del DataGridView
If CurrAppliedConfig < DataGridView1.Rows.Count Then
Dim lastRow As DataGridViewRow = DataGridView1.Rows(CurrAppliedConfig)
Dim lastCellButton As DataGridViewButtonCell = CType(lastRow.Cells(5), DataGridViewButtonCell)
Dim lastFont As Font = lastCellButton.Style.Font
' Crea un nuovo font basato su quello esistente, ma con stile Regular
If lastFont IsNot Nothing Then
lastCellButton.Style.Font = New Font(lastFont, FontStyle.Regular)
End If
End If
End If
DataGridView1.ClearSelection()
' 2. AGGIORNA I DATI DELLA RIGA ESISTENTE
Dim CfgItem As String = DataGridView1.Rows(IndexRawDataGrid).Cells("Config").Value.ToString()
' Aggiorno lo stato delle icone della lista
Dim DirToReadCfg As String = FrmMain.sDataRoot
Dim NomeFileCfg As String = DirToReadCfg & If(CfgItem = "Default", String.Empty, CfgItem) & "\CameraMng.cfg"
' Creo la nuova riga che sostituirà quella precedente
Dim riga As DataGridViewRow = DataGridView1.Rows(IndexRawDataGrid)
' Crea le celle corrispondenti alle colonne
riga.Cells(0).Value = CfgItem
Dim id As String = ReadIdCameraFromCfg(NomeFileCfg)
If Not String.IsNullOrEmpty(id) Then
' Icone CFG
If CameraListCfg.IndexOf(id) < 0 Then
riga.Cells(1).Value = GetCurrIco(2)
Else
riga.Cells(1).Value = GetCurrIco(0)
End If
' Icone CAMERA
If ComboCamera.Items.IndexOf(id) > -1 Then
riga.Cells(3).Value = GetCurrIco(2)
riga.Cells(2).Value = id
Else
riga.Cells(3).Value = GetCurrIco(0)
End If
Else
riga.Cells(1).Value = GetCurrIco(-1)
riga.Cells(3).Value = GetCurrIco(-1)
End If
riga.Cells(4).Value = "Save"
riga.Cells(5).Value = "Apply"
' 3. APPLICA IL GRASSETTO ALLA RIGA CORRENTE
Dim currentCellButton As DataGridViewButtonCell = CType(riga.Cells(5), DataGridViewButtonCell)
Dim currentFont As Font = currentCellButton.Style.Font
If currentFont Is Nothing Then
currentFont = Me.DataGridView1.Font ' Usa il font del DataGridView come base
End If
' Assegna un NUOVO oggetto Font con lo stile Bold
currentCellButton.Style.Font = New Font(currentFont, FontStyle.Bold)
' 4. AGGIORNA L'INDICE DA RICORDARE
CurrAppliedConfig = IndexRawDataGrid
' Mantengo la selezione sulla riga corrente
DataGridView1.CurrentCell = riga.Cells(0)
DataGridView1.Rows(IndexRawDataGrid).Selected = True
End Sub
Private Function ReadIdCameraFromCfg(NomeFileCfg As String) As String
Dim IDCamera As String = String.Empty
Dim reader As New StreamReader(NomeFileCfg)
Dim nfi As NumberFormatInfo = New CultureInfo("en-US", False).NumberFormat
nfi.NumberDecimalSeparator = "."
Dim TmpString As String = ""
Try
While (Not reader.EndOfStream)
TmpString = reader.ReadLine()
If TmpString.StartsWith("CameraID=") Then
IDCamera = Mid(TmpString, 10)
Exit While
End If
End While
reader.Close()
reader.Dispose()
Catch ex As Exception
MsgBox("Error in Cfg File " & TmpString)
End Try
Return IDCamera
End Function
Private Function GetCurrIco(Index As Integer) As Image
Select Case Index
Case -1
myImage = My.Resources.cross
Case 0
myImage = My.Resources.warning
Case Else
myImage = My.Resources.accept
End Select
Return myImage
End Function
Public Sub SaveIDCamera(IDConfing As String, IDCamera As String)
Dim NomeFileCfg, TmpString As String
Dim NomeFileTempCfg, DirToReadCfg As String
Dim SaveFileCfg As String
Dim nf As Integer
Dim writer As StreamWriter
Try
DirToReadCfg = FrmMain.sDataRoot & IDConfing
NomeFileCfg = DirToReadCfg & "\CameraMng.cfg"
NomeFileTempCfg = DirToReadCfg & "\CameraMngTmp.cfg"
SaveFileCfg = DirToReadCfg & "\CameraMng" & Format(Now, "yyyyMMddhhmmss") & ".cfg"
If (File.Exists(NomeFileTempCfg)) Then
File.Delete(NomeFileTempCfg)
End If
nf = FreeFile()
FileOpen(nf, NomeFileCfg, OpenMode.Input)
writer = New StreamWriter(NomeFileTempCfg)
TmpString = ""
While Not EOF(nf)
TmpString = LineInput(nf)
If Not TmpString.StartsWith("CameraID=") Then
writer.WriteLine(TmpString, CultureInfo.InvariantCulture)
End If
End While
writer.WriteLine("CameraID=" & IDCamera, CultureInfo.InvariantCulture)
FileClose(nf)
writer.Close()
File.Copy(NomeFileCfg, SaveFileCfg)
If (File.Exists(NomeFileCfg)) Then
File.Delete(NomeFileCfg)
End If
File.Copy(NomeFileTempCfg, NomeFileCfg)
File.Delete(NomeFileTempCfg)
MessageBox.Show("New ID succesfully written on '" & NomeFileCfg & "'.", "Avviso", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MsgBox("Error in Writing Cfg File " & ex.Message)
End Try
End Sub
Private Sub DataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
' Controlla se la cella corrente è nella colonna della ComboBox e se il controllo è una ComboBox
If DataGridView1.CurrentCell.ColumnIndex = DataGridView1.Columns("ComboCamera").Index AndAlso TypeOf e.Control Is ComboBox Then
Dim comboBox As ComboBox = TryCast(e.Control, ComboBox)
If comboBox IsNot Nothing Then
' Rimuovi eventuali gestori eventi precedenti per evitare eventi duplicati
' Questo è importante se l'utente modifica più volte la stessa cella
RemoveHandler comboBox.SelectedIndexChanged, AddressOf DataGridViewComboBox_SelectedIndexChanged
' Aggiungi il gestore eventi per l'evento SelectedIndexChanged della ComboBox
AddHandler comboBox.SelectedIndexChanged, AddressOf DataGridViewComboBox_SelectedIndexChanged
End If
End If
End Sub
' Questo è il gestore eventi che si attiverà quando l'utente seleziona un elemento nella ComboBox
Private Sub DataGridViewComboBox_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim comboBox As ComboBox = TryCast(sender, ComboBox)
If comboBox IsNot Nothing Then
Dim selectedValue As String = comboBox.SelectedItem.ToString()
Dim currentRowIndex As Integer = DataGridView1.CurrentCell.RowIndex
Dim IDCamera As String = If(Not IsNothing(DataGridView1.Rows(currentRowIndex).Cells("ComboCamera").Value), DataGridView1.Rows(currentRowIndex).Cells("ComboCamera").Value.ToString(), String.Empty)
If IDCamera <> selectedValue Then
DataGridView1.Rows(currentRowIndex).Cells(4).Value = "Save*"
End If
End If
End Sub
' Tutti i click sulla datagrid passono da qui
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
' Controlla che il click non sia sull'intestazione della colonna
If e.RowIndex < 0 Then Return
DataGridView1.Rows(e.RowIndex).Selected = True
If e.ColumnIndex < 0 Then Return
IndexCurrentRow = e.RowIndex
IDConfig = DataGridView1.Rows(e.RowIndex).Cells("Config").Value.ToString()
IDCamera = If(Not IsNothing(DataGridView1.Rows(e.RowIndex).Cells("ComboCamera").Value), DataGridView1.Rows(e.RowIndex).Cells("ComboCamera").Value.ToString(), String.Empty)
' Controlla se il click è avvenuto nella colonna dei bottoni (Usa il nome che hai dato alla colonna)
If Me.DataGridView1.Columns(e.ColumnIndex).Name = "SaveConfig" Then
If Not String.IsNullOrEmpty(IDConfig) And Not String.IsNullOrEmpty(IDCamera) Then
SaveIDCamera(IDConfig, IDCamera)
DataGridView1.Rows(e.RowIndex).Cells(4).Value = "Save"
RefreshDataGrid(e.RowIndex)
bIsSavedAll = True
Else
MessageBox.Show("Non è possibile salvare l'ID di una camera non connessa.", "Avviso", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End If
ElseIf Me.DataGridView1.Columns(e.ColumnIndex).Name = "ApplyConfig" Then
If Not (String.IsNullOrEmpty(IDConfig) And String.IsNullOrEmpty(IDCamera)) Then
' verifico che non sia stato salvato l'id indicato
If DataGridView1.Rows(e.RowIndex).Cells(4).Value.ToString().Contains("*"c) Then
MessageBox.Show("Salvare la configurazione prima di applicarla.", "Informazione", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
Return
End If
Dim IndCamera As Integer = FrmMain.ComboBoxCameras.Items.IndexOf(IDCamera)
FrmMain.ComboBoxCameras.SelectedIndex = IndCamera
Dim IndCameraCfg As Integer = FrmMain.ComboBoxCameraCfg.Items.IndexOf(IDConfig)
FrmMain.ComboBoxCameraCfg.SelectedIndex = IndCameraCfg
RefreshSelectedItemCfg(e.RowIndex)
End If
End If
End Sub
Private Sub SetConfig_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
' 💡 FORZA LA FINE DELLA MODALITÀ DI MODIFICA
Me.Validate()
Dim result As DialogResult
For IndexRow As Integer = 0 To DataGridView1.Rows.Count - 1
If DataGridView1.Rows(IndexRow).Cells(4).Value = "Save*" Then
' Ci sono modifiche. Chiedi all'utente cosa fare.
If bIsSavedAll Then
result = MessageBox.Show("Salvare tutte le configurazioni modificate o no?", "Attenzione", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning)
End If
Select Case result
Case DialogResult.Yes
' Salvataggio
If DataGridView1.Rows(IndexRow).Cells(0).Value = "Default" Then DataGridView1.Rows(IndexRow).Cells(0).Value = String.Empty
SaveIDCamera(DataGridView1.Rows(IndexRow).Cells(0).Value, DataGridView1.Rows(IndexRow).Cells(2).Value)
DataGridView1.Rows(IndexRow).Cells(4).Value = "Save"
RefreshDataGrid(IndexRow)
bIsSavedAll = False
Case DialogResult.No
' La finestra si chiuderà normalmente. Non fare nulla.
bIsSavedAll = True
Return
Case DialogResult.Cancel
' L'utente ha annullato l'operazione. Annulla la chiusura della finestra.
bIsSavedAll = True
e.Cancel = True
End Select
End If
Next
bIsSavedAll = True
End Sub
End Class