我用一个WebBrowser1来显示页面,希望打开任意一个页面时焦点和光标都停在页面中的第一个可以接受它们的窗口中(如输入框中),有朋友告我用WebBrowser1.OleObject.Document.ParentWindow.Focus(); 但实现不了,我在打开sohu.com网站首页时,焦点和光标都不在页面里,我希望能停在用户栏中。 请各位大虾指点!

解决方案 »

  1.   

    Eastunfail朋友:
       我走到哪里都能看到你那魅力无限的名字,呵呵。
      

  2.   

    首先要:uses MSHTML;procedure Focus(Document:IHTMLDocument2);
    var IDisp:IDispatch;
        pElement:IHTMLElement;
        i:integer;
        sID:string;
        hasID:boolean;
    begin
        hasID:=false;
        for I := 0 to Document.all.length - 1 do    // 遍历所有HTML元素
        begin
            {得到当前的IDispatch接口}
            IDisp:=Document.all.item(i,i);
            IDisp.QueryInterface(IID_IHTMLElement,pElement);
            if CompareText(pElement.tagName,'INPUT')=0 then
            begin
                hasID:=Length(pElement.id )>0;//如果该元素没有ID
                if not hasID then pElement.id :='AZXUEJFLAIER34';//设置一个新的ID
                sID:=pElement.id ;
                Document.parentWindow.execScript(Format('%s.focus();',[sID]),'JScript');
                {执行JavaScript,将焦点移动到该元素上}
                if not hasID then pElement.id :='';//恢复原来的ID.
                exit;
            end;
        end;    // for
    end;
    举个例子:procedure TForm1.FormCreate(Sender: TObject);
    begin
    WebBrowser1.Navigate('about:<INPUT%20TYPE="TEXT">');end;procedure TForm1.Button1Click(Sender: TObject);
    begin
        Focus(WebBrowser1.Document as IHTMLDocument2);
    end;你试试看,是不是可以用?呵呵....................................
      

  3.   

    Eastunfail朋友:
       你的例子能行,但当我把WebBrowser1.Navigate('about:<INPUT%20TYPE="TEXT">');改成
    WebBrowser1.Navigate('http:\\www.sohu.com');后运行就出错了,说'AZXUEJFLAIER34'
    没有定义。  另外,如果有多个INPUT,该如何识别呢?
      

  4.   

    ok!这样的可以搞定:
    procedure Focus(Document:IHTMLDocument2);
    var IDisp:IDispatch;
        pElement:IHTMLElement;
        i:integer;
    begin
        for I := 0 to Document.all.length - 1 do    // 遍历所有HTML元素
        begin
            {得到当前的IDispatch接口}
            IDisp:=Document.all.item(i,i);
            IDisp.QueryInterface(IID_IHTMLElement,pElement);
            if CompareText(pElement.tagName,'INPUT')=0 then
            begin
                Document.parentWindow.execScript(Format('document.all(%d).focus();',[i]),'JScript');
                {执行JavaScript,将焦点移动到该元素上}
                exit;
            end;
        end;    // for
    end;:)
      

  5.   

    我调试用的www.google.com做的例子.可以实现了  :)