以下全局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;
Run Code Online (Sandbox Code Playgroud)
您的消息循环是一个繁忙的循环.你应该使用GetMessage而不是PeekMessage.那是因为GetMessage阻塞直到消息被添加到队列中.
您在注释中注明了GetMessage阻止终止代码的块.通过在终止之后向线程发布消息来处理该问题.或者WM_NULL作为一般醒来,或WM_QUIT作为显式指令以退出消息循环.
尝试更像这样的东西:
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;
Run Code Online (Sandbox Code Playgroud)