C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: Drag the PictureBox icon to your window in the desired location. This creates a rectangular PictureBox instance.
Here: We use a PNG image in this code. But JPEG images and GIF images are also supported.
Event: We use the Form_Load event. To create this event handler, double-click on the enclosing window in the Designer view.
Windows Forms code that initialized PictureBox control: C#
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication24
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Construct an image object from a file in the local directory.
// ... This file must exist in the solution.
Image image = Image.FromFile("BeigeMonitor1.png");
// Set the PictureBox image property to this image.
// ... Then, adjust its height and width properties.
pictureBox1.Image = image;
pictureBox1.Height = image.Height;
pictureBox1.Width = image.Width;
}
}
}
Also: It is easy to crop a PictureBox by setting its Width and Height to the desired values.
Tip: You can add hover (mouse-over) and click events to the PictureBox in the same way as other Windows Forms controls.
But: For complex programs that display images in a specific way, the PictureBox is not ideal.
And: We can zoom the image so that it maintains its original aspect ratio. The image does not appear distorted.
Enum values:
AutoSize
CenterImage
Normal
StretchImage
Zoom
Implementation of Form_Load: C#
private void Form1_Load(object sender, EventArgs e)
{
// Set the ImageLocation property to a file on the disk.
// ... Set the size mode so that the image is correctly sized.
pictureBox1.ImageLocation = "BeigeMonitor1.png";
pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
}
Also: This example shows that the PictureBox supports the ICO format for images.
Another implementation of Form_Load: C#
private void Form1_Load(object sender, EventArgs e)
{
// Set the ImageLocation property to a URL.
// ... This example image is tiny and is the icon for The Dev Codes.
pictureBox1.ImageLocation = "http://www.dotnetCodex.com/favicon.ico";
}