Delphi – Global hook thread takes up too many CPUs, how to fix it?

The following global hook threads take up too much CPU, unless I add Sleep(10) there,
There are other solutions instead of sleep (10 milliseconds)-sleep does not look Like the best solution for my application performance. If I add too much sleep, it won’t slow down the mouse.

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

while not Terminated do
begin
MessageLoop;< br /> // 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;

Try something more like this:

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;

The following global Hook threads take up too much CPU, unless I add Sleep(10) there,
There are other solutions than sleep (10ms)-sleep doesn’t seem like the best for my application performance Solution. If I increase the sleep too much, it will not slow down the speed of the mouse.

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;

Try something more like this: < p>

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;
e nd;
end;

procedure THookThread.Stop;
begin
Terminate;
PostThreadMessage(ThreadID, WM_QUIT, 0, 0);
end;

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 3122 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.