A way to redirect keypresses from TWebBrowser to the ParentForm

坚强是说给别人听的谎言 提交于 2019-12-14 03:56:56

问题


First question. Help format it, if needed, please.

Context
I have a TWebBrowser in the main form that is used to behave like it was a printer.
So I load some HTML text in it as user do some commands in the real printer...
I want the user to be able to click and select text from the WebBrowser.

Problem
When the user clicks in the WebBrowser some of the shortcuts registered from the actions don't work anymore. For example, there is an action with shortcut F7. If the user clicks in the WebBrowser and presses F7, it does not invoke my shortcut.
I know that this is by design of the WebBrowser.

So, I thought: I want to send every key combination back to the form.
The question is: How?
If it was another control, I could use a perform(WM_KeyDown,...) in the OnKeyDown event.

Alternatives or suggestions would be appreciated too. I am very tired these past 2 days, so I could be missing something.


回答1:


Derivate TWebBrowser with an implementation of IDocHostUIHandler or use the famous EmbeddedWB

Implement the interface with an event OnTranslateAccelerator called in TranslateAccelerator

Set the event on your brwoser instance

Detect your key(s) like this:

function TBrowserPageIE.DoTranslateAccelerator(const lpMsg: PMSG; const pguidCmdGroup: PGUID; const nCmdID: DWORD): HRESULT;
begin
  result := S_FALSE;

  if lpMsg.message = WM_KEYDOWN then begin
    if lpMsg.wParam = VK_F7 then begin
      // do something here...
      result := S_OK;
    end;
  end;
end;



回答2:


An option that I tested and worked is to trap the key_code on HTML/javascript and then send that to the form using changing the document title. I will let it here hoping that help someone...

You will need add the javascript to trap the keys in the Header of the HTML page like this:

<script = ''javascript''>
  function keypresed() {
    var tecla=window.event.keyCode;

    document.title = "Command"+tecla;
    event.keyCode=0;
    event.returnValue=false;
  }
  document.onkeydown=keypresed;
</script>

Then in Webbrowser you use the onTitleChangeEvent to use the key.

var
 s:string;
begin
  if Copy(Text,0,7) = 'Command' then
  begin
    //get the key...
    s:= Copy(Text,8,Length(Text));

    // if before the webbrowser get the focus edit1 was the focused control, you will need remove that focus first...
    dummy.setfocus; 
    edit1.setfocus;

    //perform keydown
    keybd_event(StrToInt(s), 1,0,0)
  end;
end;

Well, this can be used to perform any other custom command. :)



来源:https://stackoverflow.com/questions/5796029/a-way-to-redirect-keypresses-from-twebbrowser-to-the-parentform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!