WebBrowser放大缩小可用下面几句话实现:
mshtml.IHTMLDocument2 doc = myBrowser.Document as mshtml.IHTMLDocument2;
doc.parentWindow.execScript("document.body.style.zoom=" + Zoom.ToString() + ";");
但实现效果并不太好,网页内容在浏览器中显示效果不好,除了网页本身设计有问题外,显示效果与DPI有很大的关系,所以需要根据DPI调节显示比例,具体代码:
[DllImport("gdi32.dll")]
public static extern int GetDeviceCaps(
IntPtr hdc, // handle to DC
int nIndex // index of capability
);
[DllImport("user32.dll")]
public static extern bool SetProcessDPIAware();
const int LOGPIXELSX = 88;
const int LOGPIXELSY = 90;
System.Drawing.PointF GetCurrentDIPScale()
{
System.Drawing.PointF scaleUI = new System.Drawing.PointF(1.0f, 1.0f);
try
{
SetProcessDPIAware();
IntPtr screenDC = GetDC(IntPtr.Zero);
int dpi_x = GetDeviceCaps(screenDC, LOGPIXELSX);
int dpi_y = GetDeviceCaps(screenDC, LOGPIXELSY);
scaleUI.X = (float)dpi_x / 96.0f;
scaleUI.Y = (float)dpi_y / 96.0f;
ReleaseDC(IntPtr.Zero, screenDC);
return scaleUI;
}
catch (System.Exception ex)
{
}
return scaleUI;
}
/// <summary>
/// The flags are used to zoom web browser's content.
/// </summary>
readonly int OLECMDEXECOPT_DODEFAULT = 0;
readonly int OLECMDID_OPTICAL_ZOOM = 63;
void SetZoom(WebBrowser webbrowser, int zoom)
{
try
{
if (null == webbrowser)
{
return;
}
FieldInfo fiComWebBrowser = webbrowser.GetType().GetField(
"_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
if (null != fiComWebBrowser)
{
Object objComWebBrowser = fiComWebBrowser.GetValue(webbrowser);
if (null != objComWebBrowser)
{
object[] args = new object[]
{
OLECMDID_OPTICAL_ZOOM,
OLECMDEXECOPT_DODEFAULT,
zoom,
IntPtr.Zero
};
objComWebBrowser.GetType().InvokeMember(
"ExecWB",
BindingFlags.InvokeMethod,
null, objComWebBrowser,
args);
}
}
}
catch (System.Exception ex)
{
}
}
public static readonly String AppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
public static readonly String EmptyHTMLFilePath = System.IO.Path.Combine(AppDataPath, "Empty.html");
public static readonly String EmptyHTML = @"<html><head><meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8""><style>body {overflow-y: hidden;}v\:* {behavior:url(#default#VML);}o\:* {behavior:url(#default#VML);}w\:* {behavior:url(#default#VML);}.shape {behavior:url(#default#VML);}</style></head><body></body></html>
调用方法:
private void myBrowser_LoadCompleted(object sender, NavigationEventArgs e)
{
WebBrowser browser = sender as WebBrowser;
if (null != browser)
{
browser.LoadCompleted -= new System.Windows.Navigation.LoadCompletedEventHandler(myBrowser_LoadCompleted);
System.Drawing.PointF scaleUI = GetCurrentDIPScale();
if (100 != (int)(scaleUI.X * 100))
{
SetZoom(browser, (int)(scaleUI.X * scaleUI.Y * 100));
}
}