/*VISOR DE IMAGENES - REALIZADO EN C# - MILIUCO - 27/07/2003*/

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.Text;
using System.IO;
using System.Diagnostics;

namespace Visor_de_Imagen
{
    /// <summary>
    /// Formulario que contiene un control PictureBox y unos botones
    /// para manipular de forma sencilla las imágenes.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {

        /// <summary>
        /// Variable para ser utilizada en el método btAbrir_Click
        /// </summary>
        string nombreImg="";

        private System.Windows.Forms.PictureBox pbxImg;
        private System.Windows.Forms.PictureBox pbxEmi;
        private System.Windows.Forms.ToolTip toolTip1;
        private System.Windows.Forms.OpenFileDialog dlgFile;
        private System.ComponentModel.IContainer components;
        private System.Windows.Forms.Label lbImg;
        private System.Windows.Forms.SaveFileDialog dlgSave;
        private System.Windows.Forms.Panel panel3;
        private System.Windows.Forms.MainMenu mainMenu1;
        private System.Windows.Forms.MenuItem menuItem1;
        private System.Windows.Forms.MenuItem mnAbrir;
        private System.Windows.Forms.MenuItem mnCerrar;
        private System.Windows.Forms.MenuItem mnSalir;
        private System.Windows.Forms.MenuItem mnGuardar;
        private System.Windows.Forms.MenuItem menuItem2;
        private System.Windows.Forms.MenuItem mnCopiar;
        private System.Windows.Forms.MenuItem mnReal;
        private System.Windows.Forms.MenuItem mnAjustar;
        private System.Windows.Forms.MenuItem mnFlip;
        private System.Windows.Forms.MenuItem menuItem3;
        private System.Windows.Forms.Label lbImg2;
        private System.Windows.Forms.MenuItem menuItem4;
        private System.Windows.Forms.MenuItem menuItem5;
        private System.Windows.Forms.MenuItem mnCode;

        public Form1()
        {
            //
            // Necesario para admitir el Diseñador de Windows Forms
            //
            InitializeComponent();

            //
            // TODO: agregar código de constructor después de llamar a InitializeComponent
            //
        }

        /// <summary>
        /// Limpiar los recursos que se estén utilizando.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Código generado por el Diseñador de Windows Forms
        /// <summary>
        /// Método necesario para admitir el Diseñador. No se puede modificar
        /// el contenido del método con el editor de código.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
            this.pbxImg = new System.Windows.Forms.PictureBox();
            this.pbxEmi = new System.Windows.Forms.PictureBox();
            this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
            this.lbImg = new System.Windows.Forms.Label();
            this.dlgFile = new System.Windows.Forms.OpenFileDialog();
            this.dlgSave = new System.Windows.Forms.SaveFileDialog();
            this.panel3 = new System.Windows.Forms.Panel();
            this.mainMenu1 = new System.Windows.Forms.MainMenu();
            this.menuItem1 = new System.Windows.Forms.MenuItem();
            this.mnAbrir = new System.Windows.Forms.MenuItem();
            this.mnCerrar = new System.Windows.Forms.MenuItem();
            this.mnGuardar = new System.Windows.Forms.MenuItem();
            this.mnSalir = new System.Windows.Forms.MenuItem();
            this.menuItem2 = new System.Windows.Forms.MenuItem();
            this.mnCopiar = new System.Windows.Forms.MenuItem();
            this.mnReal = new System.Windows.Forms.MenuItem();
            this.mnAjustar = new System.Windows.Forms.MenuItem();
            this.mnFlip = new System.Windows.Forms.MenuItem();
            this.menuItem4 = new System.Windows.Forms.MenuItem();
            this.menuItem5 = new System.Windows.Forms.MenuItem();
            this.mnCode = new System.Windows.Forms.MenuItem();
            this.menuItem3 = new System.Windows.Forms.MenuItem();
            this.lbImg2 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // pbxImg
            // 
            this.pbxImg.Cursor = System.Windows.Forms.Cursors.Default;
            this.pbxImg.Location = new System.Drawing.Point(64, 32);
            this.pbxImg.Name = "pbxImg";
            this.pbxImg.Size = new System.Drawing.Size(435, 328);
            this.pbxImg.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.pbxImg.TabIndex = 0;
            this.pbxImg.TabStop = false;
            // 
            // pbxEmi
            // 
            this.pbxEmi.BackColor = System.Drawing.Color.Transparent;
            this.pbxEmi.Cursor = System.Windows.Forms.Cursors.Help;
            this.pbxEmi.Image = ((System.Drawing.Image)(resources.GetObject("pbxEmi.Image")));
            this.pbxEmi.Location = new System.Drawing.Point(480, 392);
            this.pbxEmi.Name = "pbxEmi";
            this.pbxEmi.Size = new System.Drawing.Size(72, 32);
            this.pbxEmi.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
            this.pbxEmi.TabIndex = 1;
            this.pbxEmi.TabStop = false;
            this.toolTip1.SetToolTip(this.pbxEmi, "Acerca de...");
            this.pbxEmi.Click += new System.EventHandler(this.pbxEmi_Click);
            // 
            // lbImg
            // 
            this.lbImg.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.lbImg.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.lbImg.ForeColor = System.Drawing.SystemColors.ControlText;
            this.lbImg.Location = new System.Drawing.Point(0, 392);
            this.lbImg.Name = "lbImg";
            this.lbImg.Size = new System.Drawing.Size(472, 16);
            this.lbImg.TabIndex = 2;
            this.lbImg.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.lbImg.UseMnemonic = false;
            // 
            // dlgFile
            // 
            this.dlgFile.RestoreDirectory = true;
            // 
            // panel3
            // 
            this.panel3.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.panel3.Location = new System.Drawing.Point(24, 16);
            this.panel3.Name = "panel3";
            this.panel3.Size = new System.Drawing.Size(512, 360);
            this.panel3.TabIndex = 1;
            // 
            // mainMenu1
            // 
            this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                      this.menuItem1,
                                                                                      this.menuItem2,
                                                                                      this.mnCode,
                                                                                      this.menuItem3});
            // 
            // menuItem1
            // 
            this.menuItem1.Index = 0;
            this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                      this.mnAbrir,
                                                                                      this.mnCerrar,
                                                                                      this.mnGuardar,
                                                                                      this.mnSalir});
            this.menuItem1.Text = "Menú Archivo";
            // 
            // mnAbrir
            // 
            this.mnAbrir.Index = 0;
            this.mnAbrir.Text = "Abrir archivo BMP / JPG";
            this.mnAbrir.Click += new System.EventHandler(this.mnAbrir_Click);
            // 
            // mnCerrar
            // 
            this.mnCerrar.Index = 1;
            this.mnCerrar.Text = "Cerrar archivo";
            this.mnCerrar.Click += new System.EventHandler(this.mnCerrar_Click);
            // 
            // mnGuardar
            // 
            this.mnGuardar.Index = 2;
            this.mnGuardar.Text = "Guardar como...";
            this.mnGuardar.Click += new System.EventHandler(this.mnGuardar_Click);
            // 
            // mnSalir
            // 
            this.mnSalir.Index = 3;
            this.mnSalir.Text = "Salir del programa";
            this.mnSalir.Click += new System.EventHandler(this.mnSalir_Click);
            // 
            // menuItem2
            // 
            this.menuItem2.Index = 1;
            this.menuItem2.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
                                                                                      this.mnCopiar,
                                                                                      this.mnReal,
                                                                                      this.mnAjustar,
                                                                                      this.mnFlip,
                                                                                      this.menuItem4,
                                                                                      this.menuItem5});
            this.menuItem2.Text = "Menú Edición";
            // 
            // mnCopiar
            // 
            this.mnCopiar.Index = 0;
            this.mnCopiar.Text = "Copiar al portapapeles";
            this.mnCopiar.Click += new System.EventHandler(this.mnCopiar_Click);
            // 
            // mnReal
            // 
            this.mnReal.Index = 1;
            this.mnReal.Text = "Tamaño real";
            this.mnReal.Click += new System.EventHandler(this.mnReal_Click);
            // 
            // mnAjustar
            // 
            this.mnAjustar.Index = 2;
            this.mnAjustar.Text = "Ajustar a la ventana";
            this.mnAjustar.Click += new System.EventHandler(this.mnAjustar_Click);
            // 
            // mnFlip
            // 
            this.mnFlip.Index = 3;
            this.mnFlip.Text = "Voltear horizontalmente";
            this.mnFlip.Click += new System.EventHandler(this.mnFlip_Click);
            // 
            // menuItem4
            // 
            this.menuItem4.Index = 4;
            this.menuItem4.Text = "Voltear verticalmente";
            this.menuItem4.Click += new System.EventHandler(this.menuItem4_Click);
            // 
            // menuItem5
            // 
            this.menuItem5.Index = 5;
            this.menuItem5.Text = "Girar la imagen 180º";
            this.menuItem5.Click += new System.EventHandler(this.menuItem5_Click);
            // 
            // mnCode
            // 
            this.mnCode.Index = 2;
            this.mnCode.Text = "Ver código en C#";
            this.mnCode.Click += new System.EventHandler(this.mnCode_Click);
            // 
            // menuItem3
            // 
            this.menuItem3.Index = 3;
            this.menuItem3.Text = "Salir del programa";
            this.menuItem3.Click += new System.EventHandler(this.menuItem3_Click);
            // 
            // lbImg2
            // 
            this.lbImg2.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.lbImg2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
            this.lbImg2.ForeColor = System.Drawing.SystemColors.ControlText;
            this.lbImg2.Location = new System.Drawing.Point(0, 416);
            this.lbImg2.Name = "lbImg2";
            this.lbImg2.Size = new System.Drawing.Size(472, 16);
            this.lbImg2.TabIndex = 3;
            this.lbImg2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
            this.lbImg2.UseMnemonic = false;
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(562, 440);
            this.Controls.Add(this.lbImg2);
            this.Controls.Add(this.lbImg);
            this.Controls.Add(this.pbxImg);
            this.Controls.Add(this.pbxEmi);
            this.Controls.Add(this.panel3);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.Menu = this.mainMenu1;
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Visor de Imágenes - C#";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);

        }
        #endregion

        /// <summary>
        /// Punto de entrada principal de la aplicación.
        /// </summary>
        [STAThread]
        static void Main() 
        {
            Application.Run(new Form1());
        }

        //Al cargar el formulario
        private void Form1_Load(object sender, System.EventArgs e)
        {
            //this.Location = new Point(20,20); //Posición inicial del formulario
            lbImg.Text="Ninguna imagen cargada";
            lbImg2.Text = "";
        }
        
        //Menú para abrir un archivo
        private void mnAbrir_Click(object sender, System.EventArgs e)
        {
            dlgFile=new OpenFileDialog();
            dlgFile.Filter="Imágenes JPG (*.jpg)|*.jpg|Mapas de bits (*.bmp)|*.bmp";
            dlgFile.Title = "Abre una imagen JPG o BMP";
            if (dlgFile.ShowDialog()==DialogResult.OK)
            {
                nombreImg=dlgFile.FileName;
                pbxImg.Image=Image.FromFile(nombreImg);
                pbxImg.SizeMode=PictureBoxSizeMode.StretchImage;
                lbImg.Text=nombreImg;
                lbImg2.Text = "Ancho de imagen: " + pbxImg.Image.Width + " px.  /  Alto de imagen: " + pbxImg.Image.Height + " px";
            }
        }

        //Vaciar la caja de imagen y la etiqueta de información
        private void mnCerrar_Click(object sender, System.EventArgs e)
        {
            //para que solamente lo haga si hay imagen en la caja de imagen
            if (pbxImg.Image!=null)
            {
                pbxImg.Image=null;
                lbImg.Text="Ninguna imagen cargada";
                lbImg2.Text = "";
            }
        }

        //Menú que muestra la imagen a tamaño real
        private void mnReal_Click(object sender, System.EventArgs e)
        {
            //para que solamente lo haga si hay imagen en la caja de imagen
            if (pbxImg.Image!=null)
            {
                pbxImg.SizeMode=PictureBoxSizeMode.Normal;
            }
        }

        //Para guardar el archivo en otro formato (BMP a JPG, JPG a BMP)
        private void mnGuardar_Click(object sender, System.EventArgs e)
        {
            //para que solamente lo haga si hay imagen en la caja de imagen
            if (pbxImg.Image!=null)
            {
                SaveFileDialog dlgSave = new SaveFileDialog();
                dlgSave.Filter="Mapas de bits (*.bmp)|*.bmp|Imágenes JPG (*.jpg)|*.jpg";
                dlgSave.Title = "Guarda como imagen JPG o BMP";                                           
                if (dlgSave.ShowDialog()==DialogResult.OK) 
                {
                    nombreImg=dlgSave.FileName;
                    if (nombreImg.EndsWith("jpg"))
                        pbxImg.Image.Save(nombreImg,ImageFormat.Jpeg);
                    if (nombreImg.EndsWith("bmp"))
                        pbxImg.Image.Save(nombreImg,ImageFormat.Bmp);
                }
            }
        }
        
        //Menú que voltea horizontalmente la imagen
        private void mnFlip_Click(object sender, System.EventArgs e)
        {
            //para que solamente lo haga si hay imagen en la caja de imagen
            if (pbxImg.Image!=null)
            {
                pbxImg.Image.RotateFlip(RotateFlipType.RotateNoneFlipX);
                pbxImg.Refresh(); //Recarga la imagen
            }
        }

        //Menú que voltea verticalmente la imagen
        private void menuItem4_Click(object sender, System.EventArgs e)
        {
            //para que solamente lo haga si hay imagen en la caja de imagen
            if (pbxImg.Image!=null)
            {
                pbxImg.Image.RotateFlip(RotateFlipType.RotateNoneFlipY);
                pbxImg.Refresh(); //Recarga la imagen
            }
        }

        //Menú que gira 180º la imagen
        private void menuItem5_Click(object sender, System.EventArgs e)
        {
            //para que solamente lo haga si hay imagen en la caja de imagen
            if (pbxImg.Image!=null)
            {
                pbxImg.Image.RotateFlip(RotateFlipType.Rotate180FlipNone);
                pbxImg.Refresh(); //Recarga la imagen
            }
        }

        //Caja de mensaje Acerca de...
        private void pbxEmi_Click(object sender, System.EventArgs e)
        {
            MessageBox.Show("Visor de imágenes realizado en C#. Autor: MILIUCO. Fecha: 28/07/2003.\n\nEl archivo \"Visor de Imagen.html\" debe estar en la misma carpeta que el ejecutable de la aplicación.","Acerca de...",MessageBoxButtons.OK);
        }

        //Menú que ajusta la imagen
        private void mnAjustar_Click(object sender, System.EventArgs e)
        {
            //para que solamente lo haga si hay imagen en la caja de imagen
            if (pbxImg.Image!=null)
            {
                pbxImg.SizeMode=PictureBoxSizeMode.StretchImage;
            }
        }

        //Menú Salir
        private void mnSalir_Click(object sender, System.EventArgs e)
        {
            Application.Exit();
        }

        //Menú para copiar la imagen al protapapeles
        private void mnCopiar_Click(object sender, System.EventArgs e)
        {
            //para que solamente lo haga si hay imagen en la caja de imagen
            if (pbxImg.Image!=null)
            {
                fnClipboard(); //función detallada en el siguiente bloque
            }
        }

        /// <summary>
        ///Función que devuelve un objeto desde el portapapeles.
        ///La clase ClipBoard deriva de la clase Object y tiene 3 miembros:
        ///constructor / GetDataObject / SetDataObject
        /// </summary>
        private Object fnClipboard()
        {
            //Copiar imagen al portapeles
            //SetDataObject lleva 2 parámetros (objeto, booleano)
            //Si booleano es true, el objeto queda en el portapapeles
            //después de haber cerrado la aplicación
            Clipboard.SetDataObject(pbxImg.Image, true);
            //Variable objClipboard para contener el portapeles
            IDataObject objClipboard = Clipboard.GetDataObject();// método constructor
            //devuelve el portapapeles como mapa de bits
            return objClipboard.GetData (DataFormats.Bitmap);
        }

        //Mostrar el código del programa
        private void mnCode_Click(object sender, System.EventArgs e)
        {

            /// <summary>
            ///Obtener la ruta a la carpeta desde la que se ha iniciado la aplicación,
            /// </summary>
            string stRuta = Application.StartupPath;

            try //para capturar las excepciones (errores)
            {
                
                //ProcessStartInfo se utiliza para iniciar procesos
                ProcessStartInfo abrirDoc = new ProcessStartInfo();
                //Añadir a la ruta "\Visor de Imagen.html" para abrir el archivo
                abrirDoc.FileName=stRuta + "\\Visor de Imagen.html";
                //Información al usuario de la ruta obtenida en su sistema
                MessageBox.Show("La ruta a tu archivo \"Visor de Imagen.html\" parece ser:\n\n" + abrirDoc.FileName,"Archivo Visor de Imagen.html",MessageBoxButtons.OK);
                abrirDoc.Verb="open"; //modo de apertura de archivo (también puede ser edit, print...)
                abrirDoc.WindowStyle=ProcessWindowStyle.Normal; //abrir en ventana normal

                //Abrir el archivo mediante su programa asociado en Windows
                Process.Start(abrirDoc);
            }
            catch (Exception a) //Objeto Exception de nombre a
            {
                MessageBox.Show("Se ha producido la siguiente excepción:\n\n" + a.Message,"Mensaje de error"); //Mensaje relativo a la excepción lanzada
            }
        }
    
        //Menú salir
        private void menuItem3_Click(object sender, System.EventArgs e)
        {
            Application.Exit();
        }

    }
}