如何获取/设置浏览器的滚动条位置(IE / Firefox / ...)?

时间:2009-04-08 13:58:32

标签: winapi

有没有办法在Internet Explorer / Firefox中获取/设置滚动条的位置? 我希望从HTML / ASP / Javascript代码中做到这一点,但是从浏览器外部的应用程序(例如使用WinAPI),而不使用BHO。

从我现在所做的搜索来看,这似乎是不可能的,所以我在这里提出一个问题作为最后的尝试。

1 个答案:

答案 0 :(得分:2)

对于Internet Explorer,您可以使用COM自动化枚举所有活动的Internet Explorer窗口/选项卡,然后访问窗口/选项卡中显示的文档的DOM树以访问和读取滚动位置。

以下示例代码使用Delphi作为编程语言。该机制在C ++,VB或C#

中类似
var
   ShWindows:  ShellWindows;
   InetExplorer: InternetExplorer;
   Count: Integer;
   I: Integer;
   HTMLDocument: IHTMLDocument2;
   Elem: IHTMLElement2;
   ScrollPosY: Integer;
begin
   // Create ShellWindows Object
   SHWindows:= CoShellWindows.Create;

   // Number of explorer windows/tabs (win explorer and ie)
   Count:= ShWindows.Count;
   ShowMessage(Format('There are %d explorer windows open.', [Count]));

   // For all windows/tabs
   for I:= 0 to (Count - 1) do
   begin
     // Get as InetExplorer interface
     InetExplorer:= SHWindows.item(I) as InternetExplorer;

     // Check to see if this explorer window contains a web document
     if Supports(InetExplorer.Document, IHTMLDocument2, HTMLDocument) then
     begin
       // Get body Element
       Elem:= HTMLDocument.body as IHTMLElement2;
       // Read vertical scroll position
       ScrollPosY:= Elem.scrollTop;

       // If this is 0 so far, maybe there is a scroll position in root element
       if ScrollPosY = 0 then
       begin
         Elem:= HTMLDocument.body.parentElement as IHTMLElement2;
         ScrollPosY:= Elem.scrollTop;
       end;

       // Display
       ShowMessage(IntToStr(Elem.scrollTop));
     end;
   end;
end;

有关文档,请从此处开始:http://msdn.microsoft.com/en-us/library/bb773974(VS.85).aspx