Delphi TWebBrowser[9] 事件Close捕获来防止异常、禁用鼠标右键、回车Enter等键的响应方法

Delphi TWebBrowser[9] 事件Close捕获来防止异常 以及 禁用鼠标右键方法

1、事件Close捕获

原因:使用TWebBrowser,如果访问的网页有关闭窗口的JavaScript,那么TWebBrowser会被注销,而应用程序本身并没有关闭,

1)在窗体上放置一个TApplicationEvents控件

2)编写OnMessage事件

procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG;
var Handled: Boolean);
begin
  if Msg.message = WM_CLOSE then //判断是否关闭消息
  begin
    if WebBrowser1.Handle = Msg.hwnd then //验证消息是否WebBrowser发来的
    Form1.Close; //关闭窗体本身
    Handled := true;
  end;
end;

2、禁用鼠标右键

procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG;
  var Handled: Boolean);
begin
  if (Msg.message = wm_rbuttondown) or (Msg.message = wm_rbuttonup) or (msg.message = WM_RBUTTONDBLCLK)   then
    if IsChild(WebBrowser1.Handle, Msg.hwnd) then
      Handled := true;//如果有其他需要处理的,在这里加上你要处理的代码
end;

  

 3、回车Enter等键的响应

procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
const
  StdKeys =[VK_TAB, VK_RETURN, VK_DELETE, VK_BACK]; { standard   keys }
  ExtKeys =[VK_LEFT, VK_RIGHT]; { extended   keys }
  fExtended = $01000000;   { extended   key   flag }
begin
  Handled := False;
  with Msg do
    if ((Message >= WM_KEYFIRST) and (Message <= WM_KEYLAST)) and
       ((wParam in StdKeys) or   {$IFDEF   VER120}(GetKeyState(VK_CONTROL) < 0) or   {$ENDIF}
       (wParam in ExtKeys) and ((lParam and fExtended) = fExtended)) then
    try
      if IsChild(WebBrowser1.Handle, hWnd) then   //Msg.hWnd
      begin    { handles all browser related messages  处理所有与浏览器相关的消息 }
        with WebBrowser1.Application as IOleInPlaceActiveObject do
          Handled := TranslateAccelerator(Msg) = S_OK;
        if not Handled then
        begin
          Handled := True;
          TranslateMessage(Msg);
          DispatchMessage(Msg);
        end;
      end;
    except
    end;
end;

  

创建时间:2020.11.23  更新时间:2021.01.14

博客园 滔Roy https://www.cnblogs.com/guorongtao 希望内容对你所有帮助,谢谢!
原文地址:https://www.cnblogs.com/guorongtao/p/14022905.html