127 lines
5.0 KiB
C#
127 lines
5.0 KiB
C#
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;
|
|
}
|
|
}
|
|
}
|
|
}
|