You currently have JavaScript disabled on your browser.

This website uses JavaScript, and This page needs JavaScript activated to work correctly.

Please active JavaScript on your browser and then refresh this page.

PictureBox



example1

The PictureBox control is found in the System.Windows.Forms namespace within the System.Windows.Forms.dll. In this blog post I am referring to the PictureBox control that is available in C# .NET-Core (.NET 6.0) with Visual Studio 2022 (although this code example might still work OK with older .NET versions).

The purpose and function of a PictureBox control is to display an image or graphics to the user in a boxed area on a Form or dialog.

The Image or graphics displayed can be set, unset, and altered both at design time and at run time.

The PictureBox control provides a SizeMode, which can be used to control the clipping and positioning of the image in the display area.

The Size of the display can be changed both at design time and at run time by adjusting the ClientSize property.

Although the PictureBox control is displayed without any borders by default, you can change the PictureBox's BorderStyle property to to distinguish the PictureBox control object from the rest of the form, even if it contains no image.

The PictureBox control object is not a selectable control, which means that it cannot receive input focus, however you can program its MouseDown, MouseUp, and MouseMove event callback methods to handle activity and input from a users mouse.

The PictureBox control is capable of displaying Custom graphics, as well as existing Image files (Bitmap, MetaFile, Icon, Jpeg, Gif, or PNG). Animated Gif files will automatically animate while loaded and displayed.

To load and display an existing external Image file use the PictureBox's Load method. You can use the PictureBox's Image property to manipulate and alter the image or graphics displayed.

The PictureBox control can also be used to display internal images from Embedded Resources, Project Resources, ImageLists, etc..

The PictureBox control also provides an Image.Save method to allow you to easily save the current Image to an external image file.


Example Source Code

This example uses a PictureBox control, along with an OpenFileDialog component, a ToolTip component, two Label controls, one TextBox control, three Button controls, and a MessageBox object.

To add the PictureBox control to your form, you can double click on its name (i.e. PictureBox) as listed in the Toolbox window panel within the Form editor window. Alternatively, you can single click on it and then drag and drop it onto your form, to position it more closer to where you want it to be positioned at. Once it is added to the form then it will appear on the forms surface area having default control values.

After you have added the PictureBox control to your form, then once you select it then you can view and edit that objects property values in the Properties window within the Forms editor window, where you can then change the controls Name, Anchor, SizeMode, and other properties as you desire.

In the following example, I put together a little program for allowing you to browse and open an image file, displaying that image file in a PictureBox control, and advancing to the previous or next image in the selected files folder.

I added a Label, and TextBox and a Button control that will be used with opening an image file, and positioned them at the top of the Form as shown below. I renamed the Button control buttonOpen, and changed its Text property to display three dash marks. I then double clicked on it to automatically create and link a callback method to that Button's Click event into the Forms source code file. I changed the TextBox Anchor property to be Top, Left, and Right, and then changed the buttonOpen's Anchor property to be Top and Right, so that they automatically resize and reposition themselves accordingly if the user resizes the Form.

I then added two Button controls and a Label controls to handle the Previous, Next, and feedback, and positioned them to be located just below the TextBox on the Form, as shown below. I renamed the two Button controls buttonPrevious and buttonNext, and set their Text properties with Previous and Next accordingly. I then double clicked on each of those Button's to automatically create and link callback methods to their Click event's into the Forms source code file. I then renamed the Label control feedbackLabel.

After that I then added a PictureBox control to be located below the Previous and Next Button's, and resized it to fit the rest of the Form. I set its Anchor property to anchor it to Top, Left, Right, and Bottom, so that it resizes with the Form if the user resizes the Form. I set the PictureBox control objects BackColor property to Gray, so that it looks more like an image window instead of like the Forms background. I then set the PictureBox control objects SizeMode property to Zoom, so that the image displayed will automatically scale and zoom itself to fit within and centered within the PictureBox control object on the Form.

I added an OpenFileDialog and a ToolTip component to the Form by double clicking on their title names in the Tools Window of the Form editor. Since they are components and not controls then they do not take up any Form space, and therefore they appear in a separate window area below the Form within the Form editor window. I double clicked on the openFileDialog1 to automatically create and link a callback method to its FileOk event into the Forms source code file.

I then clicked on the Previous and Next Button controls and set their "ToolTip on toolTip1" property value with Previous and Next accordingly.

example2

I then edited and expanded upon the Form's source code file as shown below to complete the program:


 
// Copyright 2022 T&J Divisions, LLC	
// Designed and Developed by Tim Tolbert
// All Rights Reserved
namespace TestProgram
{
    public partial class Form1 : Form
    {
        int currentFile = 0;
        List<string> files = new List<string>();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // manually add the MouseWheel event to the PictureBox control
            pictureBox1.MouseWheel += new System.Windows.Forms.MouseEventHandler(PictureBox1_MouseWheel);

            // initialize open file dialog
            openFileDialog1.InitialDirectory = "c:\\temp\\";
            openFileDialog1.FileName = "";

            // set filter to image files only
            openFileDialog1.Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG|" +
                                    "Bitmap (*.BMP)|*.BMP|" +
                                    "Jpeg (*.JPG)|*.JPG|" +
                                    "Animation (*.GIF)|*.GIF|" +
                                    "Portable Network Graphic (*.PNG)|*.PNG";
            
            // set default button states
            buttonPrevious.Enabled = false;
            buttonNext.Enabled = false;

            // clear feedback label
            feedbackLabel.Text = "";
        }

        private void buttonNext_Click(object sender, EventArgs e)
        {
            viewNextImage();
        }

        private void buttonOpen_Click(object sender, EventArgs e)
        {
            // prompt user to select an image file to open
            openFileDialog1.ShowDialog(this);
        }

        private void buttonPrevious_Click(object sender, EventArgs e)
        {
            viewPreviousImage();
        }

        private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // display selected file path
            textBox1.Text = openFileDialog1.FileName;

            // get selected directory path
            string tempDir = Path.GetDirectoryName(openFileDialog1.FileName);
            if(tempDir.EndsWith("\\") == false)
            {
                tempDir += "\\";
            }

            // get current filter
            string[] currentFilters = openFileDialog1.Filter.Split("|")[((openFileDialog1.FilterIndex - 1) * 2) + 1].Split(";");

            // get all of the image file paths from this directory
            files.Clear();
            foreach (string filter in currentFilters)
            {
                // upper case
                files.AddRange(Directory.GetFiles(tempDir, filter.ToUpper(), SearchOption.TopDirectoryOnly).ToList());

                // lower case
                files.AddRange(Directory.GetFiles(tempDir, filter.ToLower(), SearchOption.TopDirectoryOnly).ToList());
            }

            // get index of the selected file path
            currentFile = files.IndexOf(openFileDialog1.FileName);

            // display this file in the picturebox
            try
            {
                pictureBox1.Load(openFileDialog1.FileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            // check if should enable or disable the previous and next buttons
            if (files.Count > 1)
            {
                buttonPrevious.Enabled = true;
                buttonNext.Enabled = true;
            }
            else
            {
                buttonPrevious.Enabled = false;
                buttonNext.Enabled = false;
            }

            // display current file number
            feedbackLabel.Text = Convert.ToString(currentFile + 1) + " of " + files.Count.ToString();

        }

        private void PictureBox1_MouseWheel(object sender, MouseEventArgs e)
        {
            // precheck to ensure some image is loaded
            if (files.Count <= 1) { return; }

            // check if mouse wheel scrolled up or down
            if(e.Delta > 0)
            {
                // scroll down
                viewPreviousImage();
            }
            else if (e.Delta < 0)
            {
                // scroll up
                viewNextImage();
            }
        }

        private void viewNextImage()
        { 
            // advance to next image
            currentFile++;
            
            // check if gone too far
            if (currentFile >= files.Count)
            {
                // loop back to beginning
                currentFile = 0;
            }

            // display this file path
            textBox1.Text = files[currentFile];

            // display current file number
            feedbackLabel.Text = Convert.ToString(currentFile + 1) + " of " + files.Count.ToString();

            // display this file in the picturebox
            try
            {
                pictureBox1.Load(files[currentFile]);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void viewPreviousImage()
        { 
            // advance to previous image
            currentFile--;

            // check if gone too far
            if (currentFile < 0)
            {
                // loop forward to end
                currentFile = files.Count - 1;
            }

            // display this file path
            textBox1.Text = files[currentFile];

            // display current file number
            feedbackLabel.Text = Convert.ToString(currentFile + 1) + " of " + files.Count.ToString();

            // display this file in the picturebox
            try
            {
                pictureBox1.Load(files[currentFile]);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
		
    }
}

When you run the above example then you should see something similar to the following:


example3

example4

example5

example6


Final Thoughts

Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.


orangeStarorangeStarorangeStarorangeStarorangeStar  Overall rating of 5 from 1 members

User Comments






TJDivisions© 2022