通过C#获取winforms控件的屏幕截图

时间:2011-01-12 21:34:38

标签: winforms webbrowser-control screenshot

是否可以在winforms中获取控件的屏幕截图而不在屏幕上实际显示? webBrowser组件怎么样?

1 个答案:

答案 0 :(得分:12)

是。这可以做到。

我制作了一个示例程序来完成它。原谅我的命名约定和代码组织,这很快就被掀起了。您可以对其进行修改以更好地满足您的需求,但这显示了基础知识。

我有一个包含三个控件的表单:

  • button1:具有默认设置的按钮。
  • button2:将Visible属性设置为false并将Text设置为“button2 - not visible”的按钮
  • webBrowser1:将可见性设置为false的WebBrowser控件,将大小设置为250,101(这样就适合我的表单。当你查看答案底部的捕获时,大小是相关的。你会需要相应地调整大小。)

这是Form1中的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            PrintInvisibleControl(button2, @"C:\button.jpg");
            PrintInvisibleControl(webBrowser1, @"C:\webbrowser.jpg");


        }

        private void PrintInvisibleControl(Control myControl, string filename)
        {

            Graphics g = myControl.CreateGraphics();
            //new bitmap object to save the image        
            Bitmap bmp = new Bitmap(myControl.Width, myControl.Height);
            //Drawing control to the bitmap        
            myControl.DrawToBitmap(bmp, new Rectangle(0, 0, myControl.Width, myControl.Height));
            bmp.Save(filename, ImageFormat.Jpeg);
            bmp.Dispose();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            webBrowser1.Navigate("http://www.microsoft.com");
        }

    }
}

这导致以下捕获:

alt text

alt text