Implementación de la clase CapturaImagen, donde se toma una captura de pantalla de la imagen del escaneo, la cual se almacena en carpetas separadas por fecha.

This commit is contained in:
2026-04-30 10:15:33 -06:00
parent 2e45a0562e
commit 490d76dbe3
6 changed files with 195 additions and 30 deletions

126
ScanBox/CapturaImagen.cs Normal file
View File

@@ -0,0 +1,126 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ScaBox30
{
public class CapturaImagen : IDisposable
{
private Bitmap screenshot;
/// <summary>
/// Captura una zona específica de la pantalla a partir de un PictureBox
/// </summary>
/// <param name="pictureBox">El PictureBox a capturar</param>
/// <param name="delayMs">Delay en milisegundos antes de capturar (por defecto 500ms)</param>
public Bitmap CapturarImg(PictureBox pictureBox, int delayMs = 500)
{
try
{
if (pictureBox == null)
{
MessageBox.Show("El PictureBox no puede ser nulo.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
// Forzar que la UI se redibuje antes de capturar
pictureBox.Refresh();
Application.DoEvents();
// Esperar a que la imagen se actualice completamente
System.Threading.Thread.Sleep(delayMs);
// Obtener las coordenadas en pantalla del PictureBox
Point screenLocation = pictureBox.PointToScreen(Point.Empty);
int x = screenLocation.X;
int y = screenLocation.Y;
int width = pictureBox.Width;
int height = pictureBox.Height;
// Crear una imagen con el tamaño del PictureBox
screenshot = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage(screenshot))
{
// Capturar la zona específica de la pantalla
g.CopyFromScreen(x, y, 0, 0, new Size(width, height));
}
return screenshot;
}
catch (Exception ex)
{
MessageBox.Show($"Error al capturar pantalla:\n{ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return null;
}
}
public void GuardarImg(string productNum, string operatorTag)
{
// Validar que la captura existe
if (screenshot == null)
{
MessageBox.Show("No hay captura de pantalla disponible. Realiza una captura primero.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
try
{
// Crear la carpeta de destino
string picturesPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "BoxScaner");
string capturesFolder = Path.Combine(picturesPath, Globals.consecDate.ToString("yyyy-MM-dd"));
if (!Directory.Exists(capturesFolder))
{
Directory.CreateDirectory(capturesFolder);
}
// Generar nombre de archivo con timestamp y sanitizar caracteres inválidos
string timestamp = DateTime.Now.ToString("HH-mm-ss");
string safeProductNum = Path.GetInvalidFileNameChars().Aggregate(productNum, (current, c) => current.Replace(c.ToString(), ""));
string safeOperatorTag = Path.GetInvalidFileNameChars().Aggregate(operatorTag, (current, c) => current.Replace(c.ToString(), ""));
// Formato de fecha juliano: yyyyDDD
int julianDay = Globals.consecDate.DayOfYear;
string julianDate = $"{Globals.consecDate:yyyy}{julianDay:000}";
// Formato: CONSECUTIVO_yyyyDDD_TIMESTAMP_PRODUCTO_OPERADOR.png
string fileName = Path.Combine(capturesFolder,
$"{Globals.consec:D5}_{julianDate}_{timestamp}_{safeProductNum}_{safeOperatorTag}.png");
// Guardar la captura como PNG
screenshot.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show($"Acceso denegado al guardar imagen:\n{ex.Message}", "Error de permisos", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (IOException ex)
{
MessageBox.Show($"Error al guardar imagen:\n{ex.Message}", "Error de I/O", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch (Exception ex)
{
MessageBox.Show($"Error inesperado al guardar imagen:\n{ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Libera los recursos de la captura de pantalla
/// </summary>
public void Dispose()
{
if (screenshot != null)
{
screenshot.Dispose();
screenshot = null;
}
}
}
}

View File

@@ -33,6 +33,7 @@ namespace ScaBox30.Controller
catch (Exception e) catch (Exception e)
{ {
Console.WriteLine(e); Console.WriteLine(e);
System.Windows.Forms.MessageBox.Show("Error al conectar con la BD: " + e.Message);
} }
} }

View File

@@ -66,6 +66,7 @@
this.sr2000w_ip_lbl = new System.Windows.Forms.Label(); this.sr2000w_ip_lbl = new System.Windows.Forms.Label();
this.version = new System.Windows.Forms.Label(); this.version = new System.Windows.Forms.Label();
this.reader_connector = new System.Windows.Forms.Timer(this.components); this.reader_connector = new System.Windows.Forms.Timer(this.components);
this.bttnQA = new System.Windows.Forms.Button();
this.panelTitleBar.SuspendLayout(); this.panelTitleBar.SuspendLayout();
this.panelBody.SuspendLayout(); this.panelBody.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.blackimg_picbx)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.blackimg_picbx)).BeginInit();
@@ -166,6 +167,7 @@
// panelBody // panelBody
// //
this.panelBody.BackColor = System.Drawing.Color.WhiteSmoke; this.panelBody.BackColor = System.Drawing.Color.WhiteSmoke;
this.panelBody.Controls.Add(this.bttnQA);
this.panelBody.Controls.Add(this.labelRate); this.panelBody.Controls.Add(this.labelRate);
this.panelBody.Controls.Add(this.btnConfiguración); this.panelBody.Controls.Add(this.btnConfiguración);
this.panelBody.Controls.Add(this.barcode_lbl); this.panelBody.Controls.Add(this.barcode_lbl);
@@ -274,7 +276,7 @@
this.btnBD.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(119)))), ((int)(((byte)(232))))); this.btnBD.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(119)))), ((int)(((byte)(232)))));
this.btnBD.CausesValidation = false; this.btnBD.CausesValidation = false;
this.btnBD.ForeColor = System.Drawing.Color.White; this.btnBD.ForeColor = System.Drawing.Color.White;
this.btnBD.Location = new System.Drawing.Point(1001, 609); this.btnBD.Location = new System.Drawing.Point(956, 609);
this.btnBD.Name = "btnBD"; this.btnBD.Name = "btnBD";
this.btnBD.Size = new System.Drawing.Size(44, 58); this.btnBD.Size = new System.Drawing.Size(44, 58);
this.btnBD.TabIndex = 107; this.btnBD.TabIndex = 107;
@@ -434,7 +436,7 @@
this.DataText.Multiline = true; this.DataText.Multiline = true;
this.DataText.Name = "DataText"; this.DataText.Name = "DataText";
this.DataText.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.DataText.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.DataText.Size = new System.Drawing.Size(983, 58); this.DataText.Size = new System.Drawing.Size(938, 58);
this.DataText.TabIndex = 91; this.DataText.TabIndex = 91;
// //
// TgrBtn // TgrBtn
@@ -531,7 +533,7 @@
this.version.Name = "version"; this.version.Name = "version";
this.version.Size = new System.Drawing.Size(64, 21); this.version.Size = new System.Drawing.Size(64, 21);
this.version.TabIndex = 87; this.version.TabIndex = 87;
this.version.Text = "5.1"; this.version.Text = "5.0.2";
this.version.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.version.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
// //
// reader_connector // reader_connector
@@ -540,6 +542,20 @@
this.reader_connector.Interval = 5000; this.reader_connector.Interval = 5000;
this.reader_connector.Tick += new System.EventHandler(this.reader_connector_Tick); this.reader_connector.Tick += new System.EventHandler(this.reader_connector_Tick);
// //
// bttnQA
//
this.bttnQA.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.bttnQA.BackColor = System.Drawing.Color.Maroon;
this.bttnQA.CausesValidation = false;
this.bttnQA.ForeColor = System.Drawing.Color.White;
this.bttnQA.Location = new System.Drawing.Point(1003, 609);
this.bttnQA.Name = "bttnQA";
this.bttnQA.Size = new System.Drawing.Size(44, 58);
this.bttnQA.TabIndex = 114;
this.bttnQA.Text = "QA";
this.bttnQA.UseVisualStyleBackColor = false;
this.bttnQA.Click += new System.EventHandler(this.bttnQA_Click_1);
//
// Principal // Principal
// //
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
@@ -605,5 +621,6 @@
private System.Windows.Forms.Button btnConfiguración; private System.Windows.Forms.Button btnConfiguración;
private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label9;
private System.Windows.Forms.Label labelRate; private System.Windows.Forms.Label labelRate;
private System.Windows.Forms.Button bttnQA;
} }
} }

View File

@@ -13,6 +13,7 @@ using ScaBox30.Model;
using ScaBox30.Controller; using ScaBox30.Controller;
using System.Text.Json; using System.Text.Json;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Reflection;
namespace ScaBox30 namespace ScaBox30
{ {
@@ -96,6 +97,9 @@ namespace ScaBox30
// Zebra printer variables // Zebra printer variables
ZebraController ZT231 = new ZebraController("Etiqueta.prn"); ZebraController ZT231 = new ZebraController("Etiqueta.prn");
// Screenshot capture variables
CapturaImagen capturaImagen = new CapturaImagen();
ErrorCode code_actual = ErrorCode.None; ErrorCode code_actual = ErrorCode.None;
@@ -579,6 +583,10 @@ namespace ScaBox30
this.BackColor = Color.Red; this.BackColor = Color.Red;
DialogResult dialogResult = RJMessageBox.Show("Uno o m<>s codigos son incorrectos!", "ScanBox", MessageBoxButtons.OK, MessageBoxIcon.Error); DialogResult dialogResult = RJMessageBox.Show("Uno o m<>s codigos son incorrectos!", "ScanBox", MessageBoxButtons.OK, MessageBoxIcon.Error);
this.BackColor = SystemColors.Control; this.BackColor = SystemColors.Control;
// Capturar zona del PictureBox cuando hay errores para auditor<6F>a
capturaImagen.CapturarImg(blackimg_picbx);
capturaImagen.GuardarImg(barcode_lbl.Text + "_ERROR", operatorTag);
} }
//If 1 or more codes are questionable (utr_count>0) the user has to decide if the results are added to the csv file //If 1 or more codes are questionable (utr_count>0) the user has to decide if the results are added to the csv file
@@ -609,6 +617,10 @@ namespace ScaBox30
labelRate.Text = (time.TotalMilliseconds / 1000).ToString().Substring(0, 5) + " Seg."; labelRate.Text = (time.TotalMilliseconds / 1000).ToString().Substring(0, 5) + " Seg.";
TgrBtn.Enabled = true; TgrBtn.Enabled = true;
save_data = true; save_data = true;
// Capturar zona del PictureBox despu<70>s del segundo escaneo exitoso
capturaImagen.CapturarImg(blackimg_picbx);
capturaImagen.GuardarImg(barcode_lbl.Text, operatorTag);
} }
@@ -811,6 +823,7 @@ namespace ScaBox30
m_reader?.Dispose(); m_reader?.Dispose();
m_searcher?.Dispose(); m_searcher?.Dispose();
liveviewForm1?.Dispose(); liveviewForm1?.Dispose();
capturaImagen?.Dispose();
} }
@@ -1296,6 +1309,13 @@ namespace ScaBox30
} }
} }
} }
private void bttnQA_Click_1(object sender, EventArgs e)
{
}
} }

View File

@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<root> <root>
<!-- <!--
Microsoft ResX Schema Microsoft ResX Schema
Version 2.0 Version 2.0
The primary goals of this format is to allow a simple XML format The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes various data types are done through the TypeConverter classes
associated with the data types. associated with the data types.
Example: Example:
... ado.net/XML headers & schema ... ... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader> <resheader name="version">2.0</resheader>
@@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment> <comment>This is a comment</comment>
</data> </data>
There are any number of "resheader" rows that contain simple There are any number of "resheader" rows that contain simple
name/value pairs. name/value pairs.
Each data row contains a name, and value. The row also contains a Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture. text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the Classes that don't support this are serialized and stored with the
mimetype set. mimetype set.
The mimetype is used for serialized objects, and tells the The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly: extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below. read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64 mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64 mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64 mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter : using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
--> -->

View File

@@ -215,6 +215,7 @@
<Compile Include="Ayuda.Designer.cs"> <Compile Include="Ayuda.Designer.cs">
<DependentUpon>Ayuda.cs</DependentUpon> <DependentUpon>Ayuda.cs</DependentUpon>
</Compile> </Compile>
<Compile Include="CapturaImagen.cs" />
<Compile Include="ConfigTable.cs" /> <Compile Include="ConfigTable.cs" />
<Compile Include="Controller\DbController.cs" /> <Compile Include="Controller\DbController.cs" />
<Compile Include="Controller\ZebraController.cs" /> <Compile Include="Controller\ZebraController.cs" />