我在 C# 应用程序和 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;
提前致谢。
最佳答案
您正在将消息发送到主窗口句柄。这是TForm1
实例的句柄。但是您的窗口过程附加到不同的窗口句柄,该窗口句柄是通过调用 AllocateHWnd
创建的。
一个简单的修复方法是重写 TForm1
中的 WndProc
,而不是使用 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
。在这种情况下,您需要在 C# 代码中使用 FindWindow
或 EnumWindows
来定位所需的窗口。
此外,如果您在 Delphi 中使用十六进制声明消息常量,您的代码会更清晰:
WM_TOOTHUI = $AAAA;
关于C#.Net Windows 消息到 Delphi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14650820/