C#中PictureBox控件应用实例
PictureBox控件
功能
PictureBox控件用于显示位图、GIF、JPEG、图元文件和图标格式的图形。图1所示为PictureBox控件。

图1 PictureBox控件
2.属性
PictureBox控件常用的属性及说明如表1所示。

表1 PictureBox控件常用属性及说明
下面对比较重要的属性进行详细介绍。
(1)SizeMode属性。此属性用于设置PictureBox控件将如何处理图像位置和大小。
语法:
public PictureBoxSizeModeSizeMode { get; set; }
属性值:PictureBoxSizeMode 值之一,默认为 Normal。
PictureBoxSizeMode:一个返回值,用来处理图像位置和大小。PictureBoxSizeMode的属性值及说明如表2所示。

表2 PictureBoxSizeMode的属性值及说明
(2)Image属性。此属性用于指定图片框中的图片。
语法:
public Image Image { get; set; }
属性值:要显示的Image。
示例
Image属性设置
本示例中,当程序运行时,通过PictureBox控件的Image属性设置要在控件中显示的图片。
程序主要代码如下:
this.pictureBox1.Image = imageList1.Images[0];
this.pictureBox2.Image = imageList1.Images[2];
this.pictureBox1.SizeMode= PictureBoxSizeMode.StretchImage;
3.方法
CancelAsync方法
该方法主要用于取消异步图像加载。
4.事件
PictureBox控件常用事件及说明如表3所示。

表3 PictureBox控件常用事件及说明
下面详细介绍Click事件,该事件在单击图片时发生。
语法:
public event EventHandler Click
完整程序代码如下:
★★★★★主程序文件完整程序代码★★★★★
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace _8_11
{
static class Program
{
///
/// 应用程序的主入口点。
/// [STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmPictureBox());
}
}
}
★★★★★frmPictureBox窗体设计文件完整程序代码★★★★★
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace _8_11
{
public partial class frmPictureBox : Form
{
public frmPictureBox()
{
InitializeComponent();
}
private void frmPictureBox_Load(object sender, EventArgs e)
{
this.pictureBox1.Image = imageList1.Images[0];
this.pictureBox2.Image = imageList1.Images[1];
this.pictureBox1.SizeMode= PictureBoxSizeMode.StretchImage;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
}
private void pictureBox2_Click(object sender, EventArgs e)
{
}
private void timer2_Tick_1(object sender, EventArgs e)
{
}
}
}
★★★★★frmPictureBox窗体代码文件完整程序代码★★★★★
namespace _8_11
{
partial class frmPictureBox
{
///
/// 必需的设计器变量。
/// private System.ComponentModel.IContainer components = null;
///
/// 清理所有正在使用的资源。
/// ///
如果应释放托管资源,为 true;否则为 false。
protected override void Dispose(bool disposing)