I'm going crazy with Delphi and WebBrowser component.
I created a simple application, to type HTML in a Memo and display the result inside the WebBrowser component.
But, when I click inside the WebBrowser, each HTML code update (in memo) results in the steal of the focus by the WebBrowser component.
Here is the step-by-step to reproduce the problem:
- create a new VCL application
- add a TWebBrowser component to display the html
- add a TMemo component to type the html code
insert on Memo1.OnChange event this:
if WebBrowser1.Document = nil then begin WebBrowser1.Navigate('about:blank'); while WebBrowser1.ReadyState <> READYSTATE_COMPLETE do Application.ProcessMessages; end; ms := TMemoryStream.Create; try Memo1.Lines.SaveToStream(ms); ms.Seek(0, 0); (WebBrowser1.Document as IPersistStreamInit).Load(TStreamAdapter.Create(ms)) ; finally ms.Free; end;
run the application
type the HTML inside the Memo
<html> <body> Hello WebBrowser </body> </html>
click inside the WebBrowser content
- go back to the memo and try type some more changes in HTML
- here we go*, on each key press the webbrowser component steals the focus for it!
How can I solve this and prevent the "steal of the focus" ?
Ps.: the only workaround is pressing the TAB key after clicking on WebBrowser, this prevent the webbrowser the steal the focus after new changes in html code via memo.
Solved with this workaround.
Change the Memo1.OnChange code to this:
procedure TForm1.Memo1Change(Sender: TObject);
var
ms: TMemoryStream;
begin
LockWindowUpdate(panel1.Handle); // fix: lock webbrowser parent updates
// fix: re-set the webbrowser parent to prevent focus stealing
TControl(WebBrowser1).Parent := nil;
TControl(WebBrowser1).Parent := panel1;
// fix:eof
if WebBrowser1.Document = nil then
begin
WebBrowser1.Navigate('about:blank');
while WebBrowser1.ReadyState <> READYSTATE_COMPLETE do
Application.ProcessMessages;
end;
ms := TMemoryStream.Create;
try
Memo1.Lines.SaveToStream(ms);
ms.Seek(0, 0);
(WebBrowser1.Document as IPersistStreamInit).Load(TStreamAdapter.Create(ms)) ;
finally
ms.Free;
end;
LockWindowUpdate(0); // fix: unlock webbrowser parent updates to prevent flicking!!
end;