How can I terminate a thread that has a seperate message loop?
I am writing a utility unit for the SetWindowsHookEx
API.
To use it, I'd like to have an interface like this:
var
Thread: TKeyboardHookThread;
begin
Thread := TKeyboardHookThread.Create(SomeForm.Handle, SomeMessageNumber);
try
Thread.Resume;
SomeForm.ShowModal;
finally
Thread.Free; // <-- Application hangs here
end;
end;
In my current implementation of TKeyboardHookThread
I am unable to make the thread exit correctly.
The code is:
TKeyboardHookThread = class(TThread)
private
class var
FCreated : Boolean;
FKeyReceiverWindowHandle : HWND;
FMessage : Cardinal;
FHiddenWindow : TForm;
public
constructor Create(AKeyReceiverWindowHandle: HWND; AMessage: Cardinal);
destructor Destroy; override;
procedure Execute; override;
end; function HookProc(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
var
S: KBDLLHOOKSTRUCT;
begin
if nCode < then begin
Result := CallNextHookEx(, nCode, wParam, lParam)
end else begin
S := PKBDLLHOOKSTRUCT(lParam)^;
PostMessage(TKeyboardHookThread.FKeyReceiverWindowHandle, TKeyboardHookThread.FMessage, S.vkCode, );
Result := CallNextHookEx(, nCode, wParam, lParam);
end;
end; constructor TKeyboardHookThread.Create(AKeyReceiverWindowHandle: HWND;
AMessage: Cardinal);
begin
if TKeyboardHookThread.FCreated then begin
raise Exception.Create('Only one keyboard hook supported');
end;
inherited Create('KeyboardHook', True);
FKeyReceiverWindowHandle := AKeyReceiverWindowHandle;
FMessage := AMessage;
TKeyboardHookThread.FCreated := True;
end; destructor TKeyboardHookThread.Destroy;
begin
PostMessage(FHiddenWindow.Handle, WM_QUIT, , );
inherited;
end; procedure TKeyboardHookThread.Execute;
var
m: tagMSG;
hook: HHOOK;
begin
hook := SetWindowsHookEx(WH_KEYBOARD_LL, @HookProc, HInstance, );
try
FHiddenWindow := TForm.Create(nil);
try
while GetMessage(m, , , ) do begin
TranslateMessage(m);
DispatchMessage(m);
end;
finally
FHiddenWindow.Free;
end;
finally
UnhookWindowsHookEx(hook);
end;
end;
AFAICS the hook procedure only gets called when there is a message loop in the thread.
The problem is I don't know how to correctly exit this message loop.
I tried to do this using a hidden TForm
that belongs to the thread,
but the message loop doesn't process messages I'm sending to the window handle of that form.
How to do this right, so that the message loop gets terminated on thread shutdown?
Edit: The solution I'm now using looks like this (and works like a charm):
TKeyboardHookThread = class(TThread)
private
class var
FCreated : Boolean;
FKeyReceiverWindowHandle : HWND;
FMessage : Cardinal;
public
constructor Create(AKeyReceiverWindowHandle: HWND; AMessage: Cardinal);
destructor Destroy; override;
procedure Execute; override;
end; function HookProc(nCode: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
var
S: KBDLLHOOKSTRUCT;
begin
if nCode < then begin
Result := CallNextHookEx(, nCode, wParam, lParam)
end else begin
S := PKBDLLHOOKSTRUCT(lParam)^;
PostMessage(TKeyboardHookThread.FKeyReceiverWindowHandle, TKeyboardHookThread.FMessage, S.vkCode, );
Result := CallNextHookEx(, nCode, wParam, lParam);
end;
end; constructor TKeyboardHookThread.Create(AKeyReceiverWindowHandle: HWND;
AMessage: Cardinal);
begin
if TKeyboardHookThread.FCreated then begin
raise Exception.Create('Only one keyboard hook supported');
end;
inherited Create('KeyboardHook', True);
FKeyReceiverWindowHandle := AKeyReceiverWindowHandle;
FMessage := AMessage;
TKeyboardHookThread.FCreated := True;
end; destructor TKeyboardHookThread.Destroy;
begin
PostThreadMessage(ThreadId, WM_QUIT, , );
inherited;
end; procedure TKeyboardHookThread.Execute;
var
m: tagMSG;
hook: HHOOK;
begin
hook := SetWindowsHookEx(WH_KEYBOARD_LL, @HookProc, HInstance, );
try
while GetMessage(m, , , ) do begin
TranslateMessage(m);
DispatchMessage(m);
end;
finally
UnhookWindowsHookEx(hook);
end;
end;
You need to send the WM_QUIT message to that thread's message queue to exit the thread.
GetMessage returns false if the message it pulls from the queue is WM_QUIT, so it will exit the loop on receiving that message.
To do this, use the PostThreadMessage function to send the WM_QUIT message directly to the thread's message queue.
For example:
PostThreadMessage(Thread.Handle, WM_QUIT, , );
The message pump never exits and so when you free the thread
it blocks indefinitely waiting for the Execute method to finish.
Call PostQuitMessage, from the thread, to terminate the message pump.
If you wish to invoke this from the main thread then you will need to
post a WM_QUIT to the thread.
Also, your hidden window is a disaster waiting to happen.
You can't create a VCL object outside the main thread.
You will have to create a window handle using raw Win32,
or even better, use DsiAllocateHwnd.
http://www.techques.com/question/1-10451535/How-to-exit-a-thread's-message-loop?
It turns out that it's better for everyone that you don't use a windowless message queue.
A lot of things can be unintentionally, and subtly, broken if you don't have a window for messages to be dispatched to.
Instead allocate hidden window (e.g. using Delphi's thread-unsafe AllocateHwnd
)
and post messages to it using plain old PostMessage
:
procedure TMyThread.Execute;
var
msg: TMsg;
begin
Fhwnd := AllocateHwnd(WindowProc);
if Fhwnd = then Exit;
try
while Longint(GetMessage(msg, , , )) > do // will block until a message arrives on the queue.
begin
TranslateMessage(msg);
DispatchMessage(msg);
end;
finally
DeallocateHwnd(Fhwnd);
Fhwnd := ;
end;
end;
Where we can have a plain old window procedure to handle the messages:
WM_TerminateYourself = WM_APP + ; procedure TMyThread.WindowProc(var msg: TMessage);
begin
case msg.Msg of
WM_ReadyATractorBeam: ReadyTractorBeam;
WM_TerminateYourself: PostQuitMessage(0);
else
msg.Result := DefWindowProc(Fhwnd, msg.msg, msg.wParam, msg.lParam);
end;
end;
and when you want the thread to finish, you tell it:
procedure TMyThread.Terminate;
begin
PostMessage(Fhwnd, WM_TerminateYourself, , );
end; PostThreadMessage( FThreadId, WM_QUIT, 0, 0 );
Using PostThreadMessage
is not necessarily incorrect. Raymond's article that you linked to says:
PostQuitMessage(0)
Because the system tries not to inject a WM_QUIT message at a "bad time";
instead it waits for things to "settle down" before generating the WM_QUIT message,
thereby reducing the chances that the program might be in the middle of a multi-step
procedure triggered by a sequence of posted messages.
If the concerns outlined here do not apply to your message queue,
then call PostThreadMessage
with WM_QUIT
and knock yourself out.
Otherwise you'll need to create a special signal, i.e. a user-defined message,
that allows you to call PostQuitMessage
from the thread.
How can I terminate a thread that has a seperate message loop?的更多相关文章
- Thread message loop for a thread with a hidden window? Make AllocateHwnd safe
Thread message loop for a thread with a hidden window? I have a Delphi 6 application that has a thre ...
- The eventual following stack trace is caused by an error thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access, and has no functional impact.
好久没有冒泡了,最近在新环境上搭建应用时,启动报错: INFO: Illegal access: this web application instance has been stopped alre ...
- Jmeter:运行报:Error occurred starting thread group :线程组, error message:Invalid duration 0 set in Thread Group:线程组, see log file for more details
最近在用jmeter做压测,上周五压测的脚本,今天早晨结束后. 点击同样的脚本,运行就报Error occurred starting thread group :线程组, error message ...
- Await, and UI, and deadlocks! Oh my!
It’s been awesome seeing the level of interest developers have had for the Async CTP and how much us ...
- WaitForMultipleObject与MsgWaitForMultipleObjects用法
http://blog.csdn.net/byxdaz/article/details/5638680 用户模式的线程同步机制效率高,如果需要考虑线程同步问题,应该首先考虑用户模式的线程同步方法. 但 ...
- Android Guts: Intro to Loopers and Handlers
One of the reasons I love Android API is because it contains so many useful little things. Many of t ...
- Correct thread terminate and destroy
http://www.techques.com/question/1-3788743/Correct-thread-destroy Hello At my form I create TFrame a ...
- 多线程爬坑之路-Thread和Runable源码解析
多线程:(百度百科借一波定义) 多线程(英语:multithreading),是指从软件或者硬件上实现多个线程并发执行的技术.具有多线程能力的计算机因有硬件支持而能够在同一时间执行多于一个线程,进而提 ...
- Worker Thread
http://www.codeproject.com/Articles/552/Using-Worker-Threads Introduction Worker threads are an eleg ...
随机推荐
- JS方式调用本地的可执行文件
看到一个方法,有些用,先存下来,有用的时候再用. 前几天,在IE,FIREFOX中实现了用JS方式调用本地的可执行文件.地址:www.yihaomen.com/article/js/211.htm , ...
- VS如何设置OpenCV静态编译
可以使用opencv提供的静态链接库也可以自己编译静态链接库. 1 使用opencv提供的静态链接库,位置如下图. 首先设置VS配置.有如下几个配置 1 工具->选项->项目和解决方案 ...
- 批量还原数据库 SQL Server 2008
1.如果你够懒,不想一步一步点路径,一步一步选择 2.如果你连单个备份数据库的存储过程都不想多执行,一般每还原一个需要修改数据库名 下面的脚本适合你: /*********************** ...
- JavaScript Type Conversion
Data Types 5 Data Types string, number, boolean, object, function 3 Object Types object, array, date ...
- 两款较好的Web前端性能测试工具
前段时间接手了一个 web 前端性能优化的任务,一时间不知道从什么地方入手,查了不少资料,发现其实还是蛮简单的,简单来说说. 一.前端性能测试是什么 前端性能测试对象主要包括: HTML.CSS.JS ...
- BITED数学建模七日谈之三:怎样进行论文阅读
前两天,我和大家谈了如何阅读教材和备战数模比赛应该积累的内容,本文进入到数学建模七日谈第三天:怎样进行论文阅读. 大家也许看过大量的数学模型的书籍,学过很多相关的课程,但是若没有真刀真枪地看过论文,进 ...
- TopFreeTheme精选免费模板【20130703】
今天我们给大家分享13个最新的主题模板,5款WordPress主题,5款Joomla模板,3款OpenCart主题. BowThemes – BT Folio v1.0 Template for Jo ...
- lego blocks
1.题目描述 https://www.hackerrank.com/challenges/lego-blocks 2.解法分析 这题乍看一下觉得应该可以用动态规划来做,但是却死活想不到最优子结构,在网 ...
- CodeIgniter 3.0+ 部署linux环境 session报错
codeigniter Message: mkdir(): Invalid path Filename: drivers/Session_files_driver.php 看起来像权限问题,在默认情况 ...
- POJ2406----Power Strings解题报告
Power Strings Time Limit: 3000MS Memory Limit: 65536K Total Submissions: 43514 Accepted: 18153 D ...