How to open multiple image files without using the OpenFileDialog class in Visual C# .NET or in Visual C# 2005 (822916)



The information in this article applies to:

  • Microsoft Visual C# 2005, Express Edition
  • Microsoft Visual C# .NET (2003)
  • Microsoft Visual C# .NET (2002)

SUMMARY

This step-by-step article describes how to open multiple image files without using the OpenFileDialog class. This article also includes a sample code listing that describes the concepts that are discussed in this article.

Note The sample code listing in this article does not contain error-checking. Modify the code to suit your application.

back to the top

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that are required:
  • Microsoft Windows 2000, Microsoft Windows XP, or Microsoft Windows Server 2003
  • Microsoft Visual C# .NET or Microsoft Visual C# 2005
This article assumes that you are familiar with the following topics:
  • Programming with Visual C#
  • The System.Drawing.Image class
  • The System.IO.FileStream class
back to the top

Create a Windows Application

  1. Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
  2. On the File menu, point to New, and then click Project.
  3. Under Project Types, click Visual C# Projects. Under Templates, click Windows Application.

    Note In Visual Studio 2005, under Project Types, click Visual C#. Under Templates, click Windows Application.
  4. In the Name box, type ImageDemo, and then click OK.

    By default, Form1.vb is created.
back to the top

Replace the Existing Constructor of Your Form

By default, the existing constructor of Form1 does not accept any parameters. To pass a list of images and their descriptions to the constructor of the Form1 form, modify the default constructor. To modify the default constructor, follow these steps:
  1. On the View menu, click Code.
  2. In the Class1.cs file, locate the following code in the Windows Form Designer generated code region:
    		public Form1()
    		{
    			//
    			// Required for Windows Form Designer support.
    			//
    			InitializeComponent();
    
    			//
    			// TODO: Add any constructor code after InitializeComponent call.
    			//
    		}
    
  3. Replace the code that you located in step 2 with the following code:
    		public Form1(string [] cmdArgs)
    		{
    			//
    			// Required for Windows Form Designer support.
    			//
    			InitializeComponent();  
                this.WindowState = FormWindowState.Maximized;
    
              // Call the method that opens and then displays your images.
                OpenAndDisplayImages(cmdArgs);
    		}
    
back to the top

Add a New Module to Your Project

To pass a list of images and their descriptions to the constructor of the Form1 form, add a new module to your project, and then create a new Form1 object in the Main method of your new module. The Main method accepts command-line arguments. To do this, follow these steps:
  • In the Class1.cs file, locate the Main() function, and then replace the existing code with the following code:
    		[STAThread]
    		static void Main(string[] cmdArgs) 
    		{
                /// Create a Form1 object by passing the received command-line arguments 
                /// to the constructor of Form1, and then display the new Form1 object.
                Application.Run(new Form1(cmdArgs));
    		}
    
back to the top

Add Code to Open and Then Display Images

To open and then display the list of images that are passed to the constructor of your Form1 object, follow these steps:
  • Open the Class.cs file, and then add the following code after the Main function:
            /// <summary>
            /// Declare a method to control the programming logic that you must have  
            /// to open and then to display all your images.
            /// </summary>
            /// <param name="cmdArgs">Used to store command line parameters.</param>
            private void OpenAndDisplayImages(string [] cmdArgs)
            {
                
                int count;
                /// <value>Variable to iterate through your list of images.</value>
                try
                {
                    /// Temporarily suspend the layout logic for your Form1 object.
                    this.SuspendLayout();
    
                    ///Iterate through your list of images.
                    for (count = 0; count <= cmdArgs.Length - 1; count+=2)
                    {
                        /// Call the method that opens and then displays the image that corresponds to 
                        /// the image file name that is indexed by the current value of count.
                        OpenAndDisplay(cmdArgs[count],count);
                    }
                    this.ResumeLayout(false);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
            
            /// <summary>
            /// Declare a method to open and then to display the image that 
            /// imageFileName specifies.
            /// </summary>
            /// <param name="imageFileName">Used to store Image filename.</param>
            /// <param name="count">Image offset factor.</param>
            private void OpenAndDisplay(string imageFileName , int count)
            {
                /// Declare a variable to hold a reference to your image.
                FileStream imageStream;
                try
                {
                    /// Open your image for Read access as a new FileStream.
                    imageStream = new FileStream(imageFileName,FileMode.Open,FileAccess.Read);
                    
                    /// Declare a variable to hold a reference to your PictureBox.
                    PictureBox myPictureBox = new PictureBox();
                    
                    /// Set the image for the PictureBox to reduce or to expand 
                    /// to fit the size of the PictureBox.
                    myPictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
                    
                    /// Set the location of the PictureBox based on the value of count.
                    /// Because the count is always incremented by 2, you have to multiply the value of
                    /// count by 64 so that image of size 128x128 can be propery displayed.
                    myPictureBox.Location = new System.Drawing.Point(count*64,0);
                    
                    /// Set the size of the PictureBox.
                    myPictureBox.Size = new System.Drawing.Size(128,128);
                    
                    /// Set the BorderStyle of the PictureBox.
                    myPictureBox.BorderStyle = BorderStyle.Fixed3D;
                    
                    /// Set the image of the PictureBox from the opened FileStream.
                    myPictureBox.Image = System.Drawing.Image.FromStream(imageStream);
                    
                    /// Add the PictureBox to your Form1 object.
                    this.Controls.Add(myPictureBox);
                }
                catch(FileNotFoundException ex)
                {
                    MessageBox.Show(ex.ToString ());
                }
            }
    
back to the top

Complete Code Listing

Class1.CS

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.IO;

namespace ImageDemo
{
    /// <summary>
    /// Summary description for Form1.
    /// </summary>
    public class Form1 : System.Windows.Forms.Form
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        public Form1(string [] cmdArgs)
        {
            ///
            /// Required for Windows Form Designer support.
            ///
            InitializeComponent();  
            this.WindowState = FormWindowState.Maximized;

            /// Call the method that opens and then displays your images.
            OpenAndDisplayImages(cmdArgs);
        }

        /// <summary>
        /// Clean up any resources that are being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if (components != null) 
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.Size = new System.Drawing.Size(300,300);
            this.Text = "Form1";
        }
        #endregion

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] cmdArgs) 
        {
            /// Create a Form1 object by passing the received command-line arguments 
            /// to the constructor of Form1 and then display the new Form1 object.
            Application.Run(new Form1(cmdArgs));
        }

        /// <summary>
        /// Declare a method to control the programming logic that you must have  
        /// to open and then to display all your images.
        /// </summary>
        /// <param name="cmdArgs">Used to store command line parameters.</param>
        private void OpenAndDisplayImages(string [] cmdArgs)
        {
            
            int count;
            /// <value>Variable to iterate through your list of images.</value>
            try
            {
                /// Temporarily suspend the layout logic for your Form1 object.
                this.SuspendLayout();

                ///Iterate through your list of images.
                for (count = 0; count <= cmdArgs.Length - 1; count+=2)
                {
                    /// Call the method that opens and then displays the image that corresponds to 
                    /// the image file name that is indexed by the current value of count.
                    OpenAndDisplay(cmdArgs[count],count);
                }
                this.ResumeLayout(false);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        
        /// <summary>
        /// Declare a method to open and then to display the image that 
        /// imageFileName specifies.
        /// </summary>
        /// <param name="imageFileName">Used to store Image filename.</param>
        /// <param name="count">Image offset factor.</param>
        private void OpenAndDisplay(string imageFileName , int count)
        {
            /// Declare a variable to hold a reference to your image.
            FileStream imageStream;
            try
            {
                /// Open your image for Read access as a new FileStream.
                imageStream = new FileStream(imageFileName,FileMode.Open,FileAccess.Read);
                
                /// Declare a variable to hold a reference to your PictureBox.
                PictureBox myPictureBox = new PictureBox();
                
                /// Set the image for the PictureBox to reduce or to expand 
                /// to fit the size of the PictureBox.
                myPictureBox.SizeMode = PictureBoxSizeMode.StretchImage;
                
                /// Set the location of the PictureBox based on the value of count.
                /// Because the count is always incremented by 2, you have to mutiply the value of
                /// count by 64 so that image of size 128x128 can be propery displayed.
                myPictureBox.Location = new System.Drawing.Point(count*64,0);
                
                /// Set the size of the PictureBox.
                myPictureBox.Size = new System.Drawing.Size(128,128);
                
                /// Set the BorderStyle of the PictureBox.
                myPictureBox.BorderStyle = BorderStyle.Fixed3D;
                
                /// Set the image of the PictureBox from the opened FileStream.
                myPictureBox.Image = System.Drawing.Image.FromStream(imageStream);
                
                /// Add the PictureBox to your Form1 object.
                this.Controls.Add(myPictureBox);
            }
            catch(FileNotFoundException ex)
            {
                MessageBox.Show(ex.ToString ());
            }
        }
    }
}

Note The code should be changed in Visual Studio 2005. When you create a Windows Forms project, Visual C# adds one form to the project by default. This form is named Form1. The two files that represent the form are named Form1.cs and Form1.designer.cs. You write your code in Form1.cs. The designer.cs file is where the Windows Forms Designer writes the code that implements all the actions that you performed by dragging and dropping controls from the Toolbox. For more information about the Windows Forms Designer in Visual C# 2005, visit the following Microsoft Web site: back to the top

Verify That the Code Works

  1. On the Build menu, click Build Solution.
  2. At a command prompt, change the directory path of the location of the ImageDemo.exe file that you built in step 1.
  3. At the command prompt, type the following command (that includes path and description placeholders), and then click OK to run the ImageDemo program:

    ImageDemo Path_of_ImageFile1Description_of_ImageFile1Path_of_ImageFile2Description_of_ImageFile2

    where Path of ImageFile1 and Path of ImageFile2 are the file paths of the image files on your computer.

    Note You can use file names instead of file paths if the corresponding image files are located in the same directory as the directory path that you built earlier.
  4. By default, Form1 appears. You may notice that your image files are displayed in the Form1 form.

    Note You may open and then display up to eight image files by using the sample code listing that is provided in this article.
back to the top

Troubleshooting

  • You may receive the following error message when you run the ImageDemo application:

    System.IO.FileNotFoundException

    You receive this error message because one of the file paths that you provided in step 3 of the "Verify That the Code Works" section of this article is incorrect. Your file paths may be incorrect if you do not use quotation marks for command-line arguments that contain spaces.
  • Some of your image files are not displayed on the Form1 form.

    This occurs when you provide more than eight image file names as command-line arguments. Only the first eight image files are displayed on the Form1 form. You can modify the OpenAndDisplayImages method and the OpenAndDisplay method to display more than eight images on Form1.
back to the top

Modification Type:MajorLast Reviewed:1/19/2006
Keywords:kbcode kbProgramming kbCmnDlg kbFileIO kbBitmap kbHOWTOmaster KB822916 kbAudDeveloper