问题
When I open the Google web page using:
WebBrowser1.Navigate('http://www.google.com.au/advanced_search?hl=en');
it opens with the cursor in the edit box.
So when I use:
WebBrowser1.ExecWB(OLECMDID_SELECTALL,OLECMDEXECOPT_PROMPTUSER,vaIn, vaOut);
it only copies where the cursor is. Not the whole web page, which is what I want to copy. my code is:
procedure Pause()
begin
//code to pause until page loads.
end;
procedure TForm2.Button22Click(Sender: TObject);
var s:String;
vaIn, vaOut: OleVariant;
begin
s:='http://www.google.com.au/advanced_search?hl=en';
WebBrowser1.Navigate(s);
while WebBrowser1.ReadyState <> READYSTATE_COMPLETE do
begin
Pause(1000);
end;
//------->I need to put code here so the SELECTALL line of code works.<----------
//------->So the cursor isn't in to editbox but as if it has clicked <----------
//------->the webpage <----------
WebBrowser1.ExecWB(OLECMDID_SELECTALL,OLECMDEXECOPT_PROMPTUSER,vaIn, vaOut);
end;
How to select the whole web page?
回答1:
Try focusing the body before selecting all:
((WebBrowser1.Document as IHTMLDocument2).body as IHTMLElement2).focus();
WebBrowser1.ExecWB(OLECMDID_SELECTALL, OLECMDEXECOPT_PROMPTUSER, vaIn, vaOut);
With that said a better approach would be to use document.body.innerText
to grab the text, instead of simulating a select/copy like you do.
回答2:
http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvc/thread/eef2f809-cadf-44a3-956e-e75925a4b85e suggests explicit way to select all before copying. That way directly works only when page has no frames (Google Advanced has IFRAMEs and IHTMLBodyElement.CreateTextRange fails)
But the late-binding code to be like that works in XE2/Win7x64/IE9:
procedure TForm2.btn2Click(Sender: TObject);
var HTML_Doc, oRange: OleVariant;
begin
HTML_Doc := WebBrowser1.Document;
oRange := HTML_Doc.body.createTextRange;
oRange.select();
WB_Copy(webbrowser1);
end;
WBCopy is taken from WBFunks unit http://codingrus.ru/readarticle.php?article_id=721 and boils down to ExecWB call with OLECMDID_COPY, OLECMDEXECOPT_DODEFAULT parameters.
来源:https://stackoverflow.com/questions/12512088/webbrowser-and-olecmdid-selectall