【问题标题】:SendMessage to Application.Handle not workingSendMessage 到 Application.Handle 不起作用
【发布时间】:2018-04-16 17:15:00
【问题描述】:

我创建了一个类,当它被释放时,它应该向整个应用程序传播一条自定义消息。 我用PostMessage 完成了它,它几乎没有错误

PostMessage(Application.Handle, UM_MYMESSAGE, 0, 0);

然后我意识到它应该是同步的 - 通过SendMessage

SendMessage(Application.Handle, UM_MYMESSAGE, 0, 0);

在我的表单上,我使用TApplicationEvents 组件处理消息,但只是将SendMessage 切换到PostMessage 并没有让它处理消息

procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG;
  var Handled: Boolean);
begin
  if Msg.message = UM_MYMESSAGE then
  begin
    ShowMessage('Ok');

    Handled := True;
  end;
end;

如果我通过了表单句柄但不能使用 Application.Handle... 我做错了什么?

【问题讨论】:

  • 如您所见,ApplicationEvents 只能公开发布的消息。您最好在 OnMessage 上按 F1 来确认。
  • 谢谢你的光.. 你能帮我看看如何处理这个消息吗?
  • 我不明白整个应用程序是什么意思,所以很难评论。也许你可以使用“广播”,或者安装一个钩子,或者循环表单——或者更详细地解释你的问题。
  • 我认为您通过应用程序窗口句柄甚至通过消息强制执行此操作是错误的。直接调用函数即可。
  • 我不知道你在说什么

标签: delphi sendmessage postmessage


【解决方案1】:

TApplication(Events).OnMessage 事件仅针对发布到主 UI 线程消息队列的消息触发。 发送消息直接进入目标窗口的消息过程,绕过消息队列。这就是为什么您的 OnMessage 事件处理程序可以使用 PostMessage() 而不是 SendMessage()

要捕获发送TApplication 窗口的消息,您需要使用TApplication.HookMainWindow() 而不是TApplication(Events).OnMessage,例如:

procedure TForm1.FormCreate(Sender: TObject);
begin
  Application.HookMainWindow(MyAppHook);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  Application.UnhookMainWindow(MyAppHook);
end;

function TForm1.MyAppHook(var Message: TMessage): Boolean;
begin
  if Message.Msg = UM_MYMESSAGE then
  begin
    ShowMessage('Ok');
    Result := True;
  end else
    Result := False;
end;

话虽如此,更好的解决方案是使用AllocateHWnd() 创建您自己的私人窗口,您可以将自定义消息发布/发送到,例如:

procedure TForm1.FormCreate(Sender: TObject);
begin
  FMyWnd := AllocateHWnd(MyWndMsgProc);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  DeallocateHWnd(FMyWnd);
end;

procedure TForm1.MyWndMsgProc(var Message: TMessage);
begin
  if Message.Msg = UM_MYMESSAGE then
  begin
    ShowMessage('Ok');
    Message.Result := 0;
  end else
    Message.Result := DefWindowProc(FMyWnd, Message.Msg, Message.WParam, Message.LParam);
end;

然后您可以向FMyWnd发帖/发送消息。

【讨论】:

  • 谢谢...我快到了...还没弄清楚如何使用 TApplication.HookMainWindow()...
  • 你为什么要使用 Windows 消息来调用一个函数?
猜你喜欢
  • 2023-03-30
  • 1970-01-01
  • 1970-01-01
  • 2011-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-12
  • 2014-06-01
相关资源
最近更新 更多