如何创建一个不终止的控制台应用程序?
在C ++中,控制台应用程序在其Winmain过程中可以有一个消息处理程序。
In C++,a console application can have a message handler in its Winmain procedure.Like this:
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
HWND hwnd;
MSG msg;
#ifdef _DEBUG
CreateConsole("Title");
#endif
hwnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG1), NULL, DlgProc);
PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);
while(msg.message != WM_QUIT)
{
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if(IsDialogMessage(hwnd, &msg))
continue;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}
这使得进程不会关闭,直到控制台窗口收到WM_QUIT消息。我不知道如何在delphi中做类似的事情。
This makes the process not close until the console window has received WM_QUIT message. I don't know how to do something similar in delphi.
我的需要不是一个消息处理程序,而是一个轻量级的技巧,使控制台应用程序像使用线程的GUI应用程序。这样,例如,可以处理两个Indy TCP服务器,而无需控制台应用程序终止该进程。
My need is not for exactly a message handler, but a lightweight "trick" to make the console application work like a GUI application using threads. So that, for example, two Indy TCP servers could be handled without the console application terminating the process.
我的问题:如何实现?
我不确定我是否了解你需要做什么,但可能是这样的
I'm not sure I understand what you need to do, but maybe something like this
program Project1;
{$APPTYPE CONSOLE}
uses
Forms,
Unit1 in 'Unit1.pas' {DataModule1: TDataModule};
begin
Application.Initialize;
Application.CreateForm(TDataModule1, DataModule1);
while not Application.Terminated do
Application.ProcessMessages;
end.
让你开始?它是一个控制台应用程序,将在控制台关闭时终止。您可以在数据模块中使用Indy组件。
gets you started? It is a console application, which will terminate when the console is closed. You could use the Indy components in the data module.
编辑:
没有 Forms
单元的替代方案是:
The alternative without the Forms
unit is:
program Project1;
{$APPTYPE CONSOLE}
uses
Windows;
var
Msg: TMsg;
begin
while integer(GetMessage(Msg, 0, 0, 0)) <> 0 do begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end.
我认为这将不适用于大多数Delphi组件 - 我不知道Indy ,但如果其中一个单位带来 Forms
单位,则第一个版本是IMO优选的。
I think however that this won't work with most Delphi components - I don't know about Indy, but if one of its units brings the Forms
unit in anyway, then the first version is IMO preferable.