0

Tengo un programa que se ejecuta con un formulario de windows forms, tengo un boton de inicio y uno de fin , pero una ves que se realiza el proceso todo mi formulario se bloquea y no me permite dar clic a nada del formulario, pero quiero que si me equivoque al seleccionar este si me deje terminar la ejecución del programa y este me deje oprimir el botón de fin y poder finalizar el proceso. Alguien me podría orientar de como hacer esto.

De antemano gracias. Soy nueva en windows forms , por lo que agradecería algún ejemplo grafico o algo así para entender mejor,

    private void Inicializar_Click_1(object sender, EventArgs e)
            {
                timerProceso.Interval = 100;
                txtMensaje.Text = "";
                txtProceso.Visible = false;
                timerProceso.Start();
            }
    
            private void Finalizar_Click(object sender, EventArgs e)
            {
                timerProceso.Stop();
                BarraProgreso.Value = 100;
                txtProceso.Text = "";
                txtMensaje.Text = "Proceso terminado.";
                lblTiempo.Visible = false;
                BarraProgreso.Visible = false;
            }

 private void timerProceso_Tick(object sender, EventArgs e)
         {
            BarraProgreso.Visible = false;
            BarraProgreso.Value = 0;
            txtMensaje.Text = "";

            DateTime ldatFechaActual = DateTime.Now;
            string lstrFechaHoraActual = Convert.ToDateTime(ldatFechaActual).ToString("yyyy/MM/dd H:mm");
            scheduleTimer = DateTime.Today.AddHours(20).AddMinutes(10);
            Convert.ToDateTime(scheduleTimer).ToString("yyyy/MM/dd H:mm");

            string dirMensajes = "C:\\tempInvesdoc";
            string fileName = $"\\LogMensajes{ldatFechaActual.ToString("ddMMyyyy")}.txt";
           
            try
            {
                timerProceso.Interval = 120000;
                this.BarraProgreso.Cursor = Cursors.WaitCursor;
                BarraProgreso.Maximum = 100;
                BarraProgreso.Step = 25;
                string lstrFechaInicio = dateFechaFin.Value.ToString("yyyy/MM/dd");
                string lstrFechaActual = ldatFechaActual.ToString("yyyy/MM/dd");
                
                if (lstrFechaInicio != lstrFechaActual)
                {
                    DateTime ldatFechaInicio = dateFechaInicio.Value;
                    DateTime ldatFechaFin = dateFechaFin.Value;

                    timerProceso.Enabled = false;
                    DialogResult dresulConfirmacion = MessageBox.Show("Seguro que desea iniciar?", "Mensaje", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (dresulConfirmacion == DialogResult.Yes)
                    {
                        BarraProgreso.Visible = true;
                        BarraProgreso.Value = 25;
                        BarraProgreso.PerformStep();
                        txtProceso.Visible = true;

                        if (dateFechaFin.Value.Date < ldatFechaActual || lstrFechaInicio != lstrFechaActual)
                        {
                            //Inserción de documentos por rangos
                            string lstrFechaRegistro1 = ldatFechaInicio.ToString("yyyyMMdd");
                            string lstrFechaRegistro2 = ldatFechaFin.ToString("yyyyMMdd");

                            BarraProgreso.PerformStep();
                            using (WSDocumentoInvesdoc.ServiceClient wsRPA_Invesdoc = new WSDocumentoInvesdoc.ServiceClient())
                            {
                                BarraProgreso.PerformStep();
                                string lstrInvesdoc = wsRPA_Invesdoc.plistObtenerGuiasInvesdoc(lstrFechaRegistro1, lstrFechaRegistro2);

                                int columnas = gdvRegistros.Rows.Add();
                                gdvRegistros.Rows[columnas].Cells[0].Value = ldatFechaActual.ToString("dd/MM/yyyy HH:mm:ss");
                                gdvRegistros.Rows[columnas].Cells[1].Value = ldatFechaInicio.ToString("dd/MM/yyyy") + " - " + ldatFechaFin.ToString("dd/MM/yyyy");
                                gdvRegistros.Rows[columnas].Cells[2].Value = lstrInvesdoc.ToString();

                                gdvRegistros.Rows[columnas].Cells[0].ReadOnly = true;
                                gdvRegistros.Rows[columnas].Cells[1].ReadOnly = true;
                                gdvRegistros.Rows[columnas].Cells[2].ReadOnly = true;

                                dateFechaInicio.Value = DateTime.Now;
                                BarraProgreso.PerformStep();

                                if (Directory.Exists(dirMensajes))
                                {
                                    using (var logMensajes = new StreamWriter(dirMensajes + fileName, true))
                                    {
                                        var numFilas = gdvRegistros.Rows.Count;
                                        int contador = 1;
                                        
                                        foreach (DataGridViewRow row in gdvRegistros.Rows)
                                        {
                                            if (numFilas == contador)
                                            {
                                                logMensajes.WriteLine($"{row.Cells[0].Value} | {row.Cells[1].Value} | {row.Cells[2].Value}");

                                                string lstrFechasRegistradas = row.Cells[1].Value.ToString();
                                                string lstrExcepciones = row.Cells[2].Value.ToString();
                                                string lstrExcepcionesInvesdoc = wsRPA_Invesdoc.pstringInsertaExcepciones(lstrFechasRegistradas, lstrExcepciones);
                                            }
                                            contador++;
                                        }
                                    }

                                }
}}

1 respuesta 1

0

Puedes dar uso al componente BackgroundWorker

En el enlace tienes información además de una aplicación Windows Forms de ejemplo con dos botones de iniciar y parar, una serie de calculos y la actualización de una progress bar:

using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace BackgroundWorkerSimple
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            backgroundWorker1.WorkerReportsProgress = true;
            backgroundWorker1.WorkerSupportsCancellation = true;
        }

        private void startAsyncButton_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.IsBusy != true)
            {
                // Start the asynchronous operation.
                backgroundWorker1.RunWorkerAsync();
            }
        }

        private void cancelAsyncButton_Click(object sender, EventArgs e)
        {
            if (backgroundWorker1.WorkerSupportsCancellation == true)
            {
                // Cancel the asynchronous operation.
                backgroundWorker1.CancelAsync();
            }
        }

        // This event handler is where the time-consuming work is done.
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            for (int i = 1; i <= 10; i++)
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    // Perform a time consuming operation and report progress.
                    System.Threading.Thread.Sleep(500);
                    worker.ReportProgress(i * 10);
                }
            }
        }

        // This event handler updates the progress.
        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            resultLabel.Text = (e.ProgressPercentage.ToString() + "%");
        }

        // This event handler deals with the results of the background operation.
        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled == true)
            {
                resultLabel.Text = "Canceled!";
            }
            else if (e.Error != null)
            {
                resultLabel.Text = "Error: " + e.Error.Message;
            }
            else
            {
                resultLabel.Text = "Done!";
            }
        }
    }
}
1
  • una discukpa no entiendo como este ayuda a que cuando se realice el proceso me permita darle clic a detener, ya intente con lo anterior pero no le entiendo mucho el 23 ene. a las 23:41

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.