My problem is that my form has an event to close and in fact it does it correctly as long as I do not return to where the event occurred, this means that while I browse through other windows except the initial one, it appears the message only once and if I return 2 or 3 times to the initial form, the closing window when I click on the "x" appears 2 or 3 times.
Event code:
//Metodo para cerrar la aplicacion cuando el usuario guste.
private void cierre(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
DialogResult dialogResult = MessageBox.Show("¿Esta seguro de Que quiere cerrar la aplicacion?", "Cerrar la Aplicacion", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dialogResult != DialogResult.Yes)
{
e.Cancel = true;
return;
}
}
}
Code with which I advance to the next window:
//Metodo para llevarme a la ventana de Modal_General
private void btnCompras_Click(object sender, EventArgs e)
{
this.Close();
Modal_General general = new Modal_General();
general.Show();
}
Code with which I return to my initial form.
private void btnRegresar_Click(object sender, EventArgs e)
{
this.Close();
Inicio inicio = new Inicio();
inicio.Show();
}
The closing event code is in my main form, and when I go back to my initial form and click on x, the confirmation pop-up window opens twice, I do not know if it's because maybe I'm applying inicio.Closed += (s, args) => this.Close();
, to go to the next window and then to return to the initial window.
Window that appears twice:
Complete Code of the form to which it advances:
namespace Presupuesto_DaeboSoft
{
public partial class Modal_General : Form
{
private MySqlConnection connection;
string imgPath;
string imagen;
int conteo=0;
string fecha="";
//Metodo para obtener las imagenes actuales de tu sistema
public void obtenerImagenes()
{
String Mes = DateTime.Now.Month.ToString();
PictureBox[] pics = { Enero, Febrero, Marzo, Abril, Mayo, Junio, Julio, Agosto, Septiembre, Octubre, Noviembre, Diciembre };
for (int i =0; i < Convert.ToInt32(Mes); i++)
{
imagen = pics[i].Name;
var directorio = new System.IO.DirectoryInfo(@"..\..\Imagenes\Imagenes_Modal\Usuario\" + imagen);
if (directorio.Exists==true) {
conteo = directorio.GetFiles().Length-1;
}
imgPath = @"..\..\Imagenes\Imagenes_Modal\Usuario\"+imagen+@"\"+imagen+conteo + ".jpeg";
if (imgPath != null && Directory.Exists(@"..\..\Imagenes\Imagenes_Modal\Usuario\"+imagen) == true)
{
pics[i].Image = Image.FromFile(imgPath);
}
}
}
//Metodo para no cambiar de tamaño el formulario y que se ejecute de forma central
public void notSize()
{
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.CenterToScreen();
}
//Constructor del Formulario
public Modal_General()
{
Base_de_Datos.Conexion conn = new Base_de_Datos.Conexion();
connection = conn.iniciarBD();
InitializeComponent();
obtenerImagenes();
notSize();
//Me genera un ciclo que rellena de imagenes los meses despues del actual.
//Tambien me desabilita los botones de cambio inecesario.
String Dia = DateTime.Now.Day.ToString();
String Mes = DateTime.Now.Month.ToString();
String Año = DateTime.Now.Year.ToString();
fecha = Año + "-" + Mes + "-" + Dia;
lblDia.Text = Dia;
lblMes.Text = Mes;
lblAño.Text = Año;
PictureBox[] pics = { Enero, Febrero, Marzo, Abril, Mayo, Junio, Julio, Agosto, Septiembre, Octubre, Noviembre, Diciembre };
Button[] botones = { btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn10, btn11, btn12 };
for (int MesE = Convert.ToInt16(Mes); MesE < pics.Length; MesE++)
{
pics[MesE].Image = Image.FromFile(@"..\..\Imagenes\Imagenes_Modal\Default\NoAplica.png");
pics[MesE].Enabled = false;
botones[MesE].Visible = false;
}
}
private void Modal_General_Load(object sender, EventArgs e)
{
}
//Eventos clic que llaman el metodo de cambiar imagen
//*************************************************************************************\
private void btn1_Click(object sender, EventArgs e)
{
Cambiar_Imagen("Enero",Enero);
}
private void btn2_Click(object sender, EventArgs e)
{
Cambiar_Imagen("Febrero",Febrero);
}
private void btn3_Click(object sender, EventArgs e)
{
Cambiar_Imagen("Marzo",Marzo);
}
private void btn4_Click(object sender, EventArgs e)
{
Cambiar_Imagen("Abril", Abril);
}
private void pic12_Click(object sender, EventArgs e)
{
Cambiar_Imagen("Diciembre", Diciembre);
}
private void pic6_Click(object sender, EventArgs e)
{
Cambiar_Imagen("Junio", Junio);
}
private void pic7_Click(object sender, EventArgs e)
{
Cambiar_Imagen("Julio", Julio);
}
private void pic8_Click(object sender, EventArgs e)
{
Cambiar_Imagen("Agosto", Agosto);
}
private void pic9_Click(object sender, EventArgs e)
{
Cambiar_Imagen("Septiembnre", Septiembre);
}
private void pic10_Click(object sender, EventArgs e)
{
Cambiar_Imagen("Octubre", Octubre);
}
private void pic11_Click(object sender, EventArgs e)
{
Cambiar_Imagen("Noviembre", Noviembre);
}
private void pic5_Click(object sender, EventArgs e)
{
Cambiar_Imagen("Mayo", Mayo);
}
//*************************************************************************************\
//Metodo para cambiar la imagen del picturebox
public void Cambiar_Imagen(string valor, PictureBox picture)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Image Files(*.jpg; *.jpeg; *.gif;*.png)|*.jpg; *.jpeg; *.gif;*.png";
if (open.ShowDialog() == DialogResult.OK)
{
string ext = Path.GetExtension(open.FileName);
var fileInfo = new FileInfo(open.FileName);
picture.Image = new Bitmap(open.FileName);
Image img = System.Drawing.Image.FromFile(open.FileName);
string archivoOrigen = open.FileName;
string rutaDestino = @"..\..\Imagenes\Imagenes_Modal\Usuario";
string archivoDestino = System.IO.Path.Combine(rutaDestino, open.SafeFileName);
DirectorySecurity securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule("NQ054", FileSystemRights.FullControl, AccessControlType.Allow));
DirectoryInfo di = Directory.CreateDirectory(@"..\..\Imagenes\Imagenes_Modal\Usuario", securityRules);
if (Directory.Exists(@"..\..\Imagenes\Imagenes_Modal\Usuario") == true)
{
if (!di.CreateSubdirectory(@"" + valor).Exists)
{
DirectoryInfo subcarpeta = di.CreateSubdirectory(@"" + valor);
}
int fCount = Directory.GetFiles(@"..\..\Imagenes\Imagenes_Modal\Usuario\" + valor, "*", SearchOption.TopDirectoryOnly).Length;
string ruta = @"..\..\Imagenes\Imagenes_Modal\Usuario\" + valor + "\\" + valor + fCount + ".jpeg";
string archivo = valor + fCount + ".jpeg";
File.Copy(archivoOrigen, ruta, true);
connection.Open(); //se abre conexion
string Query = "Insert Into Imagenes (Ruta, Tipo, NumeroI,Archivo,FechaCambio) values('" + ruta + "','" + valor + "',2,'" + archivo + "','"+fecha+"')";
MySqlCommand Conn = new MySqlCommand(Query, connection);
MySqlDataReader reader = Conn.ExecuteReader();
connection.Close(); //se cierra conexion
}
else
{
DirectoryInfo subcarpeta = di.CreateSubdirectory(@"" + valor);
int fCount = Directory.GetFiles(@"..\..\Imagenes\Imagenes_Modal\Usuario\" + valor, "*", SearchOption.TopDirectoryOnly).Length;
string ruta = @"..\..\Imagenes\Imagenes_Modal\Usuario\" + valor + "\" + valor + fCount + ".jpeg";
string archivo = valor + fCount + ".jpeg";
File.Copy(archivoOrigen, archivo, true);
connection.Open(); // se abre conexion
string Query = "Insert Into Imagenes (Ruta, Tipo, NumeroI,ArchivoFechaCambio) values('" + ruta + "','" + valor + "',2,'" + archivo + "',1,'"+fecha+"')";
MySqlCommand Conn = new MySqlCommand(Query, connection);
MySqlDataReader reader = Conn.ExecuteReader();
connection.Close(); //se cierra conexion
}
}
}
private void btnRegresar_Click(object sender, EventArgs e)
{
this.Close();
Inicio inicio = new Inicio();
inicio.Show();
}
}
}
Complete Code of the Start Form:
namespace Presupuesto_DaeboSoft
{
public partial class Inicio : Form
{
int contador = 0;
//constructor de la clase, inicia todos los componentes
public Inicio()
{
InitializeComponent();
}
//Metodo para no cambiar de tamaño el formulario y que se ejecute de forma central
public void notSize()
{
this.FormBorderStyle = FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.CenterToScreen();
}
//Metodo que carga los elementos iniciales del formulario
private void Inicio_Load(object sender, EventArgs e)
{
notSize();
String quincena = calendario.TodayDate.Day.ToString();
int dia = int.Parse(quincena);
if (dia > 15)
{
lblQuincena.Text = "2";
}
else
{
lblQuincena.Text = "1";
}
}
//Metodo para cerrar la aplicacion cuando el usuario guste.
private void cierre(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
DialogResult dialogResult = MessageBox.Show("¿Esta seguro de Que quiere cerrar la aplicacion?", "Cerrar la Aplicacion", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dialogResult != DialogResult.Yes)
{
e.Cancel = true;
return;
}
}
}
//Metodo que me da la hora actual.
private void horaActual(object sender, EventArgs e)
{
String tiempo = DateTime.Now.ToString("HH:mm:ss");
lblTiempo.Text = "Hora Actual: " + tiempo;
}
//Metodo para llevarme a la ventana de Modal_General
private void btnCompras_Click(object sender, EventArgs e)
{
this.Close();
Modal_General general = new Modal_General();
general.Show();
}
}
}