今回はC#でフォームを作りピクチャボックスで画像を表示してみます。
ファイル名:Form1.cs
code>using System; using System.IO; using System.Windows.Forms; using System.Collections.Generic; using System.Drawing; // ピクチャボックスのサンプル public class Form1 : Form { // コンストラクタ public Form1() { this.Load += Form1_Load; this.Resize += Form1_Resize; this.Shown += Form1_Resize; } // ピクチャボックスの生成 private PictureBox CreatePicbox() { PictureBox m = new PictureBox(); m.Name = "PICBOX"; // クリックイベント m.Click += (sender, e) => { MessageBox.Show("クリックされた。", "EVENT"); }; return m; } // ピクチャボックスにローカルファイルをセット private void SetLocatFileToPicBox(string path) { var picbox = (PictureBox)this.Controls["PICBOX"]; if (picbox.Image != null) { picbox.Image.Dispose(); } using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { picbox.Image = Image.FromStream(fs); } } // Form1のLoadイベント private void Form1_Load(object sender, EventArgs e) { var controls = new List<Control>(); // ピクチャボックスの設置 controls.Add(this.CreatePicbox()); // コントロールの追加 this.Controls.AddRange(controls.ToArray()); this.SetLocatFileToPicBox("H:\\ps1\\resx_image\\folder1.png"); } // Form1のリサイズイベント private void Form1_Resize(object sender, EventArgs e) { var form = (Form)sender; var picbox = (PictureBox)form.Controls["PICBOX"]; picbox.Size = form.ClientSize; } }
ファイル名:PicboxSumple.cs
code>using System; using System.Windows.Forms; class BaseForm { [STAThread] static void Main() { Form form = new Form1(); Application.Run(form); } }
ファイル名:PicboxSample.csproj
code><Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <AssemblyName>PicboxSample</AssemblyName> <OutputPath>Bin\</OutputPath> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> </PropertyGroup> <ItemGroup> <Compile Include="*.cs"/> </ItemGroup> <Target Name="Build" Inputs="@(Compile)" Outputs="$(OutputPath)$(AssemblyName).exe"> <MakeDir Directories="$(OutputPath)" Condition="!Exists('$(OutputPath)')" /> <Csc Sources="@(Compile)" TargetType="winexe" OutputAssembly="$(OutputPath)$(AssemblyName).exe"/> </Target> <Target Name="Clean" > <Delete Files="$(OutputPath)$(AssemblyName).exe" /> </Target> <Target Name="Rebuild" DependsOnTargets="Clean;Build" /> <Target Name="Run" DependsOnTargets="Rebuild"> <Exec Command="$(OutputPath)$(AssemblyName).exe" /> </Target> </Project>
ファイル名:folder1.png
画像ファイルへのパスは実行環境に合わせる必要がありますので適時へんこうしてください。
ビルドして実行すると以下のようなフォームが表示されます。
コメント