2

我在 ac# 应用程序和 delphi 应用程序之间的 Windows 消息有问题。

我用c#到c#和delphi到delphi做了一些例子,但我不能用c#到delphi

这是我相关的 C# 应用程序,它是 WM 发件人代码

    void Game1_Exiting(object sender, EventArgs e)
    {
        Process[] Processes = Process.GetProcesses();

        foreach(Process p in Processes)
            if(p.ProcessName == Statics.MainAppProcessName)
                SendMessage(p.MainWindowHandle, WM_TOOTHUI, IntPtr.Zero, IntPtr.Zero);


    }

    private const int WM_TOOTHUI = 0xAAAA;
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public static extern int SendMessage(IntPtr hwnd, [MarshalAs(UnmanagedType.U4)] int Msg, IntPtr wParam, IntPtr lParam);

这是我相关的 delphi 应用程序,它是 WM 接收器代码

    const
      WM_TOOTHUI = 43690;
    type
      private
        MsgHandlerHWND : HWND;
        procedure WndMethod(var Msg: TMessage);

    procedure TForm1.WndMethod(var Msg: TMessage);
    begin
      if Msg.Msg = WM_TOOTHUI then
      begin
        Caption := 'Message Recieved';
      end;
    end;

    procedure TForm1.FormCreate(Sender: TObject);
    begin
      MsgHandlerHWND := AllocateHWnd(WndMethod);
    end;

提前致谢。

4

1 回答 1

5

您正在将消息发送到主窗口句柄。那是 的实例的句柄TForm1。但是您的窗口过程附加到不同的窗口句柄,该窗口由您调用创建的AllocateHWnd.

一个简单的解决方法是覆盖WndProcinTForm1而不是使用AllocateHWnd.

// in your class declaration:
procedure WndProc(var Message: TMessage); override;

// the corresponding implementation:
procedure TForm1.WndProc(var Message: TMessage);
begin
  if Msg.Msg = WM_TOOTHUI then
  begin
    Caption := 'Message Recieved';
  end; 
  inherited;
end;

或者正如 Mason 所说,您可以使用 Delphi 的特殊消息处理语法:

// in your class declaration:
procedure WMToothUI(var Message: TMessage); message WM_TOOTHUI;

// the corresponding implementation:
procedure TForm1.WMToothUI(var Message: TMessage);
begin
  Caption := 'Message Recieved';
end;

也有可能p.MainWindowHandle甚至不是主窗口的句柄。如果您使用的是旧版本的 Delphi,则p.MainWindowHandle可能会找到应用程序的句柄,Application.Handle. 在这种情况下,您将需要FindWindowEnumWindows在您的 C# 代码中找到所需的窗口。

此外,如果您在 Delphi 中使用十六进制声明消息常量,您的代码会更清晰:

WM_TOOTHUI = $AAAA;
于 2013-02-01T16:34:36.060 回答