Microsoft KB Archive/822916

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

Article ID: 822916

Article Last Modified on 11/26/2007

-

APPLIES TO


 * Microsoft Visual C# 2005 Express Edition
 * Microsoft Visual C# .NET 2003 Standard Edition
 * Microsoft Visual C# .NET 2002 Standard Edition

-





For a Microsoft Visual Basic .NET version of this article, see 827046.

IN THIS TASK

 * SUMMARY
 * Requirements
 * Create a Windows Application
 * Replace the Existing Constructor of Your Form
 * Add a New Module to Your Project
 * Add Code to Open and Then Display Images
 * Complete Code Listing
 * Verify That the Code Works
 * Troubleshooting
 * REFERENCES



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.
 * 1) 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:  On the View menu, click Code.  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. //       }   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: ///        /// Declare a method to control the programming logic that you must have /// to open and then to display all your images. ///        /// <param name=&quot;cmdArgs&quot;>Used to store command line parameters. private void OpenAndDisplayImages(string [] cmdArgs) {           int count; /// Variable to iterate through your list of images. 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); }       }        ///         /// Declare a method to open and then to display the image that /// imageFileName specifies. ///        /// <param name=&quot;imageFileName&quot;>Used to store Image filename. /// <param name=&quot;count&quot;>Image offset factor. 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 ); }       } </li></ul>

back to the top

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 description for Form1. ///    public class Form1 : System.Windows.Forms.Form {       ///         /// Required designer variable. ///        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); }

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

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

///        /// The main entry point for the application. ///        [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)); }

///        /// Declare a method to control the programming logic that you must have /// to open and then to display all your images. ///        /// <param name=&quot;cmdArgs&quot;>Used to store command line parameters. private void OpenAndDisplayImages(string [] cmdArgs) {           int count; /// Variable to iterate through your list of images. 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); }       }        ///         /// Declare a method to open and then to display the image that /// imageFileName specifies. ///        /// <param name=&quot;imageFileName&quot;>Used to store Image filename. /// <param name=&quot;count&quot;>Image offset factor. 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:

http://msdn2.microsoft.com/en-us/library/ms173077.aspx

back to the top

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

ImageDemo    

where  and   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.</li> 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.</li></ol>

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 &quot;Verify That the Code Works&quot; 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.</li> 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.</li></ul>

back to the top

<div class="references_section">