全局钩子线程占用太多CPU,如何修复?

 手机用户2502854251 发布于 2022-12-20 18:32

以下全局Hook线程占用太多CPU,除非我在那里添加Sleep(10),是否有另一个解决方案而不是Sleep(10 ms) - 休眠看起来不像是我的应用程序性能的最佳解决方案.如果我增加太多睡眠,它也不会减慢鼠标的速度.

  procedure THookThread.Execute;
    begin
      hookhandle := SetWindowsHookEx(WH_MOUSE_LL, @LowLevelMouseHook, Hinstance, 0);

     while not Terminated do
      begin    
        MessageLoop;
      //  Sleep(10);
      end;

      UnHookWindowsHookEx(hookhandle);
      hookhandle := 0;

    end;

procedure THookThread.MessageLoop;
var
  msg: TMsg;
begin
  while PeekMessage(msg, 0, 0, 0, PM_NOREMOVE) do
  begin
    TranslateMessage(msg);
    DispatchMessage(msg);
  end;
end;

David Heffer.. 6

您的消息循环是一个繁忙的循环.你应该使用GetMessage而不是PeekMessage.那是因为GetMessage阻塞直到消息被添加到队列中.

您在注释中注明了GetMessage阻止终止代码的块.通过在终止之后向线程发布消息来处理该问题.或者WM_NULL作为一般醒来,或WM_QUIT作为显式指令以退出消息循环.

2 个回答
  • 尝试更像这样的东西:

    procedure THookThread.Execute;
    var
      msg: TMsg;
      ret: LongInt;
    begin
      //create the message queue...
      PeekMessage(msg, 0, WM_USER, WM_USER, PM_NOREMOVE);
    
      hookhandle := SetWindowsHookEx(WH_MOUSE_LL, @LowLevelMouseHook, Hinstance, 0);
      if hookhandle = 0 then RaiseLastOSError; 
    
      try
        while GetMessage(msg, 0, 0, 0) and (not Terminated) do
        begin
          TranslateMessage(msg);
          DispatchMessage(msg);
        end;
      finally
        UnHookWindowsHookEx(hookhandle);
        hookhandle := 0;
      end;
    end;
    
    procedure THookThread.Stop;
    begin
      Terminate;
      PostThreadMessage(ThreadID, WM_QUIT, 0, 0);
    end;
    

    2022-12-20 18:34 回答
  • 您的消息循环是一个繁忙的循环.你应该使用GetMessage而不是PeekMessage.那是因为GetMessage阻塞直到消息被添加到队列中.

    您在注释中注明了GetMessage阻止终止代码的块.通过在终止之后向线程发布消息来处理该问题.或者WM_NULL作为一般醒来,或WM_QUIT作为显式指令以退出消息循环.

    2022-12-20 18:35 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有