c# - WatiN NativeElement.GetElementBounds() - 测量单位是什么?

标签 c# .net watin

当我使用 WatiN 进行测试时,我喜欢保存屏幕截图。有时我并不真的需要整个浏览器窗口的图片 - 我只需要一张我正在测试的元素的图片。

我尝试使用以下代码保存元素的图片,结果生成了 block 框的图片,因为 elementBounds.Top 指向远远超过屏幕底部的像素位置。 elementBounds.Width 和 .Height 值似乎也只有它们应有的一半左右。

这是 WatiN 错误,还是我必须以某种方式将这些属性转换为像素的不同度量单位?

public static void SaveElementScreenshot
    (WatiN.Core.IE ie, WatiN.Core.Element element, string screenshotPath)
{
    ScrollIntoView(ie, element);
    ie.BringToFront();

    var ieClass = (InternetExplorerClass) ie.InternetExplorer;

    Rectangle elementBounds = element.NativeElement.GetElementBounds();
    int left = ieClass.Left + elementBounds.Left;
    int top = ieClass.Top + elementBounds.Top;
    int width = elementBounds.Width;
    int height = elementBounds.Height;

    using (var bitmap = new Bitmap(width, height))
    {
        using (Graphics graphics = Graphics.FromImage(bitmap))
        {
            graphics.CopyFromScreen
                (new Point(left, top), Point.Empty, new Size(width, height));
        }

        bitmap.Save(screenshotPath, ImageFormat.Jpeg);
    }
}

最佳答案

看起来这是一个 WatiN 错误。正如在 WatiN issue tracker site 上讨论的那样,Internet Explorer 元素的“get bounds”方法如下所示:

internal static Rectangle GetHtmlElementBounds(IHTMLElement element)
{
    int offsetLeft = element.offsetLeft;
    int offsetTop = element.offsetTop;
    for (IHTMLElement element2 = element.parentElement; element2 != null; element2 = element2.parentElement)
    {
        offsetLeft += element2.offsetLeft;
        offsetTop += element2.offsetTop;
    }
    int width = element.offsetWidth / 2;
    return new Rectangle(offsetLeft, offsetTop, width, element.offsetHeight / 2);
}

错误在于它将 offsetWidth 和 offsetHeight 除以 2。

我将对 element.NativeElement.GetElementBounds 的调用替换为调用我自己的“GetElementBounds”方法,它按照我希望的方式工作:

private static Rectangle GetElementBounds(Element element)
{
    var ieElem = element.NativeElement as WatiN.Core.Native.InternetExplorer.IEElement;
    IHTMLElement elem = ieElem.AsHtmlElement;

    int left = elem.offsetLeft;
    int top = elem.offsetTop;

    for (IHTMLElement parent = elem.offsetParent; parent != null; parent = parent.offsetParent)
    {
        left += parent.offsetLeft;
        top += parent.offsetTop;
    }

    return new Rectangle(left, top, elem.offsetWidth, elem.offsetHeight);
}

唯一剩下的问题是 top 和 left 属性没有补偿浏览器窗口“chrome”的大小,因此元素屏幕截图比应有的更靠下和靠右。

在我弄清楚如何弥补这一点之前,我通过在截取屏幕截图之前将浏览器设置为“全屏”模式来避免它。

关于c# - WatiN NativeElement.GetElementBounds() - 测量单位是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2850735/

相关文章:

c# - 除了 LOCALMACHINE - 没有管理权限的注册表之外,我可以在哪里放置普通用户数据

c# - 如何捕获 OutlookContact.Write 事件?

c# - 等待 "Unable to cast COM object"异常

c# - 如何更改列标题文本大小

c# - Autofixture - 创建带余数的 float 、 double 或小数

c# - 解析日志文件时性能下降

.net - 微软推荐的程序目录

c# - 在 UI 线程中任务完成时显示表单

automated-tests - Watin 和 Fluent 自动化 - 引用当前浏览器

c# - Watin - 使用 ConfirmDialogHandler 处理确认对话框