C#:Formを画像キャプチャする方法(Form全体とクライアント領域のみと)
2018/06/10
C#のGUIコントロールにはDrawToBitmap
というメソッドがあって、これを使うと簡単にキャプチャ画像が撮れます。
フォーム全体のキャプチャ画像はthis.DrawToBitmap(...)
でキャプチャ可能ですが、クライアント領域のみのキャプチャはちょっとだけテクニックを使います。
[ad#top-1]
Form全体をキャプチャする場合
サンプルプログラムは以下の通りです。ボタンを押すとフォーム全体がキャプチャされるようになっています。UIがWindows7調に変わってしまうのが気になるのですが…。
ソースコードは以下の通りです。
using System; using System.Drawing; using System.Windows.Forms; class FormCapture{ static void Main(string[] args){ Application.Run(new MainWindow(args)); } } class MainWindow : Form{ public MainWindow(string[] args){ this.StartPosition = FormStartPosition.CenterScreen; this.Width = 400; this.Height = 200; this.Text = "Test"; new Label(){ Text = "Label", Location = new Point(10, 10), Parent = this, }; Button btn1 = new Button(){ Text = "OK", Location = new Point(10, 100), Parent = pane, }; btn1.Click += new EventHandler(BtnClicked); } private void BtnClicked(object sender, EventArgs e){ Bitmap bmp = new Bitmap(this.Width, this.Height); this.DrawToBitmap(bmp, new Rectangle(0, 0, this.Width, this.Height)); bmp.Save("capture.png"); bmp.Dispose(); MessageBox.Show("保存しました"); } }
クライアント領域のみをキャプチャする場合
次にクライアント領域のみをキャプチャする場合です。以下がサンプルプログラムです。
これはちょっとしたテクニック(というほどのものではないですが)を使います。それは、ボタンやラベルをフォームに直接貼り付けるのではなく、一旦パネルを噛ましてその上に配置させます。そのパネルをキャプチャすることでクライアント領域のみをキャプチャするようになります。
using System; using System.Drawing; using System.Windows.Forms; class FormCapture{ static void Main(string[] args){ Application.Run(new MainWindow(args)); } } class MainWindow : Form{ private Panel pane; public MainWindow(string[] args){ this.StartPosition = FormStartPosition.CenterScreen; this.Width = 400; this.Height = 200; this.Text = "Test"; pane = new Panel(){ Dock = DockStyle.Fill, Parent = this, }; new Label(){ Text = "Label", Location = new Point(10, 10), Parent = pane, }; Button btn1 = new Button(){ Text = "OK", Location = new Point(10, 100), Parent = pane, }; btn1.Click += new EventHandler(BtnClicked); } private void BtnClicked(object sender, EventArgs e){ Bitmap bmp = new Bitmap(pane.Width, pane.Height); pane.DrawToBitmap(bmp, new Rectangle(0, 0, pane.Width, pane.Height)); bmp.Save("capture.png"); bmp.Dispose(); MessageBox.Show("保存しました"); } }
変わったところは、Panelを敷いてその上にコントロールを配置したことと、ボタンイベントの2行を変えました。
Bitmap bmp = new Bitmap(pane.Width, pane.Height); pane.DrawToBitmap(bmp, new Rectangle(0, 0, pane.Width, pane.Height));
[ad#ad-1]
スポンサーリンク