C#实现将网页保存成图片的网页拍照功能
本文实例主要实现了网页照相机程序的功能。C#实现将网页保存成图片格式,简单实现网页拍照,主要是基于ActiveX组件的网页快照类,AcitveX必须实现IViewObject接口。因此读者完全可扩展此类将其用于你的C#软件项目中。在此特别感谢作者:随飞提供的代码。
主要功能代码如下:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Runtime.InteropServices;
usingSystem.Runtime.InteropServices.ComTypes;
usingSystem.Drawing;
usingSystem.Windows.Forms;
namespaceSnapLibrary
{
///<summary>
///ActiveX组件快照类,用于网页拍照,将网页保存成图片
///AcitveX必须实现IViewObject接口
///作者:随飞
///</summary>
publicclassSnapshot
{
///<summary>
///取快照
///</summary>
///<paramname="pUnknown">Com对象</param>
///<paramname="bmpRect">图象大小</param>
///<returns></returns>
publicBitmapTakeSnapshot(objectpUnknown,RectanglebmpRect)
{
if(pUnknown==null)
returnnull;
//必须为com对象
if(!Marshal.IsComObject(pUnknown))
returnnull;
//IViewObject接口
SnapLibrary.UnsafeNativeMethods.IViewObjectViewObject=null;
IntPtrpViewObject=IntPtr.Zero;
//内存图
BitmappPicture=newBitmap(bmpRect.Width,bmpRect.Height);
GraphicshDrawDC=Graphics.FromImage(pPicture);
//获取接口
objecthret=Marshal.QueryInterface(Marshal.GetIUnknownForObject(pUnknown),
refUnsafeNativeMethods.IID_IViewObject,outpViewObject);
try
{
ViewObject=Marshal.GetTypedObjectForIUnknown(pViewObject,typeof(SnapLibrary.UnsafeNativeMethods.IViewObject))asSnapLibrary.UnsafeNativeMethods.IViewObject;
//调用Draw方法
ViewObject.Draw((int)DVASPECT.DVASPECT_CONTENT,
-1,
IntPtr.Zero,
null,
IntPtr.Zero,
hDrawDC.GetHdc(),
newNativeMethods.COMRECT(bmpRect),
null,
IntPtr.Zero,
0);
Marshal.Release(pViewObject);
}
catch(Exceptionex)
{
Console.WriteLine(ex.Message);
throwex;
}
//释放
hDrawDC.Dispose();
returnpPicture;
}
}
}