C# 一個函數建立 PictureBox 圖片選單 範例

先說一下會這樣寫是因為會抓取網路上圖片 存在陣列裡面 這樣寫很方便選圖片~

這邊秀出原始代碼 部分是需要自訂的~

private void pictureBox_圖片選擇_DoubleClick(object sender, EventArgs e)

{

圖片選單((PictureBox)sender);

}
Image[] 海報images;

public void 圖片選單(PictureBox 使用的圖片框)

{

Form 表單 = new Form

{

FormBorderStyle = FormBorderStyle.FixedSingle,// 設置 Form 的 FormBorderStyle 屬性為 FixedSingle 或 FixedDialog,以禁止調整大小

MaximizeBox = false, // 禁用最大化按鈕

MinimizeBox = false, // 禁用最小化按鈕

AutoSize = true, // 設置 Form 的 AutoSize 和 AutoSizeMode 屬性,使其根據內容自動調整大小

AutoSizeMode = AutoSizeMode.GrowAndShrink,

StartPosition = FormStartPosition.CenterParent, // 設置 Form 的 StartPosition 屬性為 CenterParent,使其在父視窗的正中間顯示

Text = "選擇圖片"

};

FlowLayoutPanel flowLayoutPanell = new FlowLayoutPanel

{

Size = new Size(1420, 500),

AutoScroll = true,

Location = new Point(0, 0),

Name = "flowLayoutPanell"

};

表單.Controls.Add(flowLayoutPanell);

foreach (var image in 海報images ?? Enumerable.Empty<Image>())

{

PictureBox pictureBox = new PictureBox

{

Image = image,

SizeMode = PictureBoxSizeMode.Zoom,

Size = new Size(340, 500),

Margin = new Padding(5)

};

pictureBox.Click += (sender, e) => {

PictureBox pictureBox = sender as PictureBox;

if (pictureBox != null)

{

使用的圖片框.Image = pictureBox.Image;

表單.Close();

}

};

flowLayoutPanell.Controls.Add(pictureBox);

}

// 添加 Button

Button 增加圖片button = new Button();

增加圖片button.Text = "增加圖片";

增加圖片button.Location = new Point(1220, 500);

增加圖片button.Size = new Size(200, 40);

增加圖片button.Click += (sender, e) => {

OpenFileDialog openFileDialog = new OpenFileDialog

{

Filter = "Image Files|*.jpg;*.jpeg;*.png;*.bmp",

Multiselect = true

};

if (openFileDialog.ShowDialog() == DialogResult.OK)

{

foreach (string fileName in openFileDialog.FileNames)

{

Image newImage = Image.FromFile(fileName);

List<Image> imageList = 海報images == null ? new List<Image>() : 海報images.ToList();

imageList.Add(newImage);

海報images = imageList.ToArray();

PictureBox pictureBox = new PictureBox

{

Image = newImage,

SizeMode = PictureBoxSizeMode.Zoom,

Size = new Size(340, 500),

Margin = new Padding(5)

};

pictureBox.Click += (sender, e) => {

PictureBox pictureBox = sender as PictureBox;

if (pictureBox != null)

{

使用的圖片框.Image = pictureBox.Image;

表單.Close();

}

};

flowLayoutPanell.Controls.Add(pictureBox);

}

}

};

表單.Controls.Add(增加圖片button);

表單.ShowDialog();

}

下面來張展試圖

留言