1. Image Slider


Snap shot of Image Slider
Image slider snap shot


Hi, friends in this tutorial i will guide you about how to make a simple image slider in c# using win forms step by step. This application is created using Object Oriented Programming pattern

Step 1.
   Before start the task you need visual studio 2010  which has .net framework 4.0 by default.

Step 2.
   Design the look of Image slider using Toolbox control (left side in visual studio). 
   Remember you need the following controls for this application (Image Slider) :

  1. pictureBox1
  2. Buttons
  3. Radio buttons
  4. check boxes
  5. Timer 
  6. OpenFileDialogue
  7. SaveFileDialogue
  8. contecxtMenuStrip
After creating your design by drag and drop,  your image slider looks like same as above image.

Step 3.
  Create new CLASS file like this image shown bellow and give that file name 
  ImageSliderRunner.cs


creating new class file in visual studio
Creating new class file in visual studio


Step 4.
  copy and paste the following code into your ImageSliderRunner.cs file
  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace ImageSliderDemo
{
    sealed class ImageSliderRunner
    {
        private static string[] pics;
       
        private static string[] imagePaths;

        public static int Counter = 0;

        public static void SetImages()
        {

            imagePaths = Directory.GetFiles("images");
            ImageSliderRunner.pics = new string[imagePaths.Length];

            for (int i = 0; i < imagePaths.Length; i++)
                 pics[i] = imagePaths[i];

        }

       
        public static string PlaySlides()
        {

            Counter++;
            return pics[Counter];
        }


        public static string InitialPic()
        {
            return pics[0];
        }


        public static string NextImage()
        {

            Counter++;
            return pics[Counter];

        }


        public static string PrevImage()
        {

            Counter--;
            return pics[Counter];
        }


        public static string GetPath(string path)
        {

            return path;
        }


        public static bool ImportImages(string sourceFile , string copeidFile)
        {

            File.Copy(sourceFile, copeidFile);
            
            return true;
        }



        public static int TotalImages()
        {

            return ImageSliderRunner.pics.Length;
           
        }

        public static string RemovePicture()
        {
            
                return ImageSliderRunner.pics[Counter];
           
        }


        public static string GetCurrentPicture()
        {

            return ImageSliderRunner.pics[Counter];
        }


      
        public static bool DoSavePicture(string picture, string DesPath)
        {

            File.Copy(picture, DesPath);
            return true;

        }


        public static string SavePerference(string resource)
        {

            File.WriteAllText("storePrefe.txt", resource);
            return resource;
        }


        public static string GetPreference()
        {

            string[] pref = File.ReadAllLines("storePrefe.txt");
            return pref[0];

        }
    }

}


Step 5.
   Now open your Form1.cs [Design] file which contains your all controls means your
   image slider design (buttons, UI etc). after open it your file look likes as bellow:


Form1.cs [Design] file selected in visual studio
Form1.cs [Design] file selected in visual studio

Step 6.
  at this point you have to create events in code behind file of this  Form1.cs [Design]  file
  but remember you must create events by double clicking at > this button and you will 
  notice that event can be seen at right side in toolbox which marked as red circle.


Creating an event in visual studio
Creating an event in visual studio


Step 7.
  When you double click at < button in step 6. the click event has created and along this it's
  code behind file (Form1.css) also created as bellow. Remember some points here which is

  1.   This is the code behind file Form1.cs which contains your all registered events and response the user interaction such as NEXT image PREV image etc.
  2. This events called the methods from class file which is mentioned in Step 4. 
  3. All the main logic is written in that class file ImageSliderRunner.cs



Code behind file with event creation
Code behind file with event creation

Step 8. (final step)
  Copy and paste the following code into your code behind file (Form1.css) which is mentioned
  in Step 7.

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ImageSliderDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void Form1_Load(object sender, EventArgs e)
        {

           
                ImageSliderRunner.SetImages();

            if (Convert.ToBoolean(ImageSliderRunner.GetPreference()))
            {

                TopMost = Convert.ToBoolean(ImageSliderRunner.GetPreference());
                checkBox1.Checked = true;
            }

            label4.Text = ImageSliderRunner.TotalImages().ToString() + " Pictures \n are exists in \n ImageSlider \n right now!";

            timer1.Interval = 5000;
            radioButton5.Checked = true;
            pictureBox1.BorderStyle = BorderStyle.None;
            Zoombtn.Checked = true;

            try
            {
                pictureBox1.Image = Image.FromFile(ImageSliderRunner.InitialPic());
            }
            catch (Exception)
            {



            }
            groupBox4.Enabled = false;
        }
      

        private void NextImage(object sender, EventArgs e)
        {

            try
            {
                
                pictureBox1.Image = Image.FromFile(ImageSliderRunner.NextImage());
                ImageSliderRunner.SetImages();
                label4.Text = ImageSliderRunner.TotalImages().ToString() + " Pictures \n are exists in \n ImageSlider \n right now!";
            }
            catch (IndexOutOfRangeException)
            {

                ImageSliderRunner.Counter = -1;
            }

        }

        private void PreImage(object sender, EventArgs e)
        {

            try
            {
                pictureBox1.Image = Image.FromFile(ImageSliderRunner.PrevImage());
              
            }
            catch (IndexOutOfRangeException)
            {

             
            }


           


        }

        private void StrachImage(object sender, EventArgs e)
        {


            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

        }

        private void ZoomImage(object sender, EventArgs e)
        {

            pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;

        }

        private void NoneR(object sender, EventArgs e)
        {

            pictureBox1.BorderStyle = BorderStyle.None;

        }

        private void FixSingle(object sender, EventArgs e)
        {

            pictureBox1.BorderStyle = BorderStyle.FixedSingle;
        }

        private void FixD(object sender, EventArgs e)
        {

            pictureBox1.BorderStyle = BorderStyle.Fixed3D;

        }

        private void top(object sender, EventArgs e)
        {

            this.TopMost = true;

        }

        private void PlaySlides(object sender, EventArgs e)
        {
            if (button4.Text == ">")
            {
                
                timer1.Start();
                BtDisabled();
                button4.Text = "| |";
                groupBox4.Enabled = true;
            }

            else
            {

                timer1.Stop();
                this.BtEnables();
                button4.Text = ">";
                groupBox4.Enabled = false;


            }
        }
    
        private void timer1_Tick(object sender, EventArgs e)
        {
         

            try
            {
               
                pictureBox1.Image = Image.FromFile(ImageSliderRunner.PlaySlides());
                label4.Text = ImageSliderRunner.TotalImages().ToString() + " Pictures \n are exists in \n ImageSlider \n right now!";
                ImageSliderRunner.SetImages();
                

            }
            catch (IndexOutOfRangeException)
            {
               ImageSliderRunner.Counter = -1;


            }
        }


        private void BtDisabled()
        {

            button1.Enabled = false;
            button2.Enabled = false;

        }


        private void BtEnables()
        {

            button1.Enabled = true;
            button2.Enabled = true;

        }

        private new void Top(object sender, EventArgs e)
        {
            


            if (checkBox1.Checked)
                TopMost = Convert.ToBoolean(ImageSliderRunner.SavePerference("true"));
                

           
            else
                TopMost = Convert.ToBoolean(ImageSliderRunner.SavePerference("false"));
               
            
        }

        private void Normal(object sender, EventArgs e)
        {

            timer1.Interval = 5000;

        }

        private void Fast(object sender, EventArgs e)
        {

            timer1.Interval = 1000;

        }

        private void Slow(object sender, EventArgs e)
        {
            timer1.Interval = 2500;

        }

        private void FollowMe(object sender, EventArgs e)
        {


             System.Diagnostics.Process.Start("https://www.facebook.com/Dotnetc?ref=hl");

        }

        private void Site(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://www.aijaz.netne.net");
        }

        private void personal(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://www.facebook.com/aijazali.abro.9");
        }

        private void ImportImages(object sender, EventArgs e)
        {

            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                string path = ImageSliderRunner.GetPath(@"images/" + openFileDialog1.SafeFileName);
                
                if (File.Exists(path))
                {
                    MessageBox.Show("This Picture is Already Exists in ImageSlider...!", "ImageSlider", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                else
                {

                    if (ImageSliderRunner.ImportImages(openFileDialog1.FileName, path))
                    {
                        
                        MessageBox.Show("This Picture is Successfully Added in ImageSlider...!" , "ImageSlider" , MessageBoxButtons.OK , MessageBoxIcon.Information);
                        
                       
                        
                    }
                    

                }

            }
                

        }

        private void RemovePic(object sender, EventArgs e)
        {

            //MessageBox.Show(ImageSliderRunner.RemovePicture());
            //File.Delete("images/sliders.jpg");
            //File.Delete(ImageSliderRunner.imagePaths);

           // MessageBox.Show("Deleted...");
        }

        private void ExportPicture(object sender, EventArgs e)
        {
          
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (ImageSliderRunner.DoSavePicture(ImageSliderRunner.GetCurrentPicture(), saveFileDialog1.FileName))
                {

                    MessageBox.Show("This Picture is Successfully Saved...!", "ImageSlider", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }


            }


        }

        private void aboutThisAppToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void ShortImport(object sender, EventArgs e)
        {

            this.ImportImages(this , null);



        }

        private void ShortExport(object sender, EventArgs e)
        {
            this.ExportPicture(this, null);
        }

        private void RemovePics(object sender, EventArgs e)
        {

            if (ImageSliderRunner.TotalImages() != 0)
            {
                
                DialogResult result = MessageBox.Show("WARNING ! \nImageSlider need to be closed before delete one / more pictures, after deletion you can re-open ImageSlider ! \n\n Do you want to delete picture / pictures ?", "ImageSlider", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start("images");
                    this.Close();

                }

            }

            else
            {

                
                MessageBox.Show("No more pictures are exists in ImageSlider for deletion !", "ImageSlider", MessageBoxButtons.OK, MessageBoxIcon.Stop);
               
            }
           
        }

        private void Refresh(object sender, EventArgs e)
        {

            ImageSliderRunner.SetImages();

        }   
              

    }
}

REMEMBER:

  • Above code will work perfect 
  • But you MUST explicitly registered ALL events which is defined in above code such as   [private void RemovePics(object sender, EventArgs e) ] if you will not do that. the apps must be generate errors.
  • Do not forget the create 1 files and 1 folder
  • create folder named [images] inside the bin -> debug folder because when you add images in slider every time that image copy in that folder
  • create .txt file named [storePrefe.txt] inside  bin -> debug.

FINALLY IF YOU WENT RIGHT THE IMAGE SLIDER WILL PERFECT WORK FOR YOU.
  1. Any image can be added and removed from slider
  2. Any image can be saved from slider
  3. Produced slide show next play and prev images
THANKS I HOPE YOU HAVE ENJOYED CODE

1 comment: