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

时间:2014-09-18 08:49:47

标签: delphi

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

  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;

2 个答案:

答案 0 :(得分:6)

您的消息循环是一个繁忙的循环。您应该使用GetMessage代替PeekMessage。这是因为GetMessage阻塞,直到消息被添加到队列中。

您在评论中注意到GetMessage阻止了您的终止代码。通过在终止之后向线程发布消息来处理该问题。 WM_NULL作为一般唤醒,或WM_QUIT作为退出消息循环的显式指令。

答案 1 :(得分:5)

尝试更像这样的东西:

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;