如何创建一个纯winapi窗口

net*_*boy 6 delphi

目标是在两个线程之间创建通信,其中一个是主线程.我正在寻找的是创建一个占用较少资源的窗口,并将其用于仅接收消息.

你有什么可以推荐我的?

And*_*and 7

这是仅限消息的窗口.我在上一个问题中编写了一个Delphi发送+接收系统示例.


Nat*_*Nat 7

您需要做的是在您的线程中设置一个消息循环,并在主线程中使用AllocateHWnd来向后和向前发送消息.这很简单.

在你的线程执行函数中有以下内容:

procedure TMyThread.Execute;
begin
  // this sets up the thread message loop
  PeekMessage(LMessage, 0, WM_USER, WM_USER, PM_NOREMOVE);

  // your main loop
  while not terminated do
  begin
    // look for messages in the threads message queue and process them in turn.
    // You can use GetMessage here instead and it will block waiting for messages
    // which is good if you don't have anything else to do in your thread.
    while PeekMessage(LMessage, 0, WM_USER, $7FFF, PM_REMOVE) do
    begin
      case LMessage.Msg of
      //process the messages
      end;
    end;

    // do other things. There would probably be a wait of some 
    // kind in here. I'm just putting a Sleep call for brevity
    Sleep(500);

  end;
end;
Run Code Online (Sandbox Code Playgroud)

要向您的主题发送消息,请执行以下操作:

PostThreadMessage(MyThread.Handle, WM_USER, 0, 0);
Run Code Online (Sandbox Code Playgroud)

在主线程方面,使用AllocateHWnd(在Classes单元中)设置一个窗口句柄,并传递一个WndProc方法.AllocateHWnd非常轻巧,易于使用:

TMyMessageReciever = class
private
  FHandle: integer;

  procedure WndProc(var Msg: TMessage);

public
  constructor Create;
  drestructor Destroy; override;

  property Handle: integer read FHandle;

end;

implementation

constructor TMyMessageReciever.Create;
begin
  inherited Create;
  FHandle := Classes.AllocateHWnd(WndProc);
end;

destructor TMyMessageReciever.Destroy;
begin
  DeallocateHWnd(FHandle);
  inherited Destroy;
end;

procedure TMyMessageReciever.WndProc(var Msg: TMessage);
begin
  case Msg.Msg of
  //handle your messages here
  end;
end;
Run Code Online (Sandbox Code Playgroud)

并使用其中任何一个发送消息SendMessage,这将阻止直到消息已被处理,或者PostMessage异步执行.

希望这可以帮助.

  • 或者,你不需要在主线程上使用`AllocateHwnd()`,特别是如果你想减少资源.使用`PostThreadMessage()`使用`MainThreadID`变量作为目标线程ID将消息直接发布到主线程消息队列,然后使用`TApplication.OnMessage`事件接收消息.您可以通过查看`TMsg.hwnd`成员来区分线程消息和窗口消息,对于线程消息,该成员将为零. (3认同)