0

我正在使用描述一些状态和值的自定义类:

  class MyClass
    {
        int State;
        String Message;
        IList<string> Values;
    }

由于应用程序架构,表单交互使用消息及其基础结构(SendMessage/PostMessage、WndProc)。问题是 - 如何使用 SendMessage/PostMessage 将 MyClass 的实例发送到 WndProc?在我的代码中,PostMessage 的定义如下:

[DllImport("user32.dll", SetLastError = true)]
public static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);

所以,我需要在我的自定义消息编号下方以某种方式发送和一个 MyClass 实例,所以在 WndProc 中我可以将它用于逻辑需求。这是可能的?

4

1 回答 1

2

你将无法做到这一点。托管语言中的指针毫无意义,当不再引用它们时,它们通常会被重新定位并杀死。好吧,也许您可​​以使用不安全的代码和固定指针来实现某种以这种方式工作的东西(正在进行中),但这将是您的厄运。

如果您只想进行进程内通信,请注意跨线程通信的影响。

如果您需要跨进程通信,请参阅此线程: C# 中的 IPC 机制 - 用法和最佳实践

编辑:

通过 SendMessage 发送 uniqueID 以获取序列化对象。我不建议这样做,因为它容易被黑客攻击和出错,但您要求:

发送消息时:

IFormatter formatter = new BinaryFormatter();
string filename = GetUniqueFilenameNumberInFolder(@"c:\storage"); // seek a freee filename number -> if 123.dump is free return 123 > delete those when not needed anymore
using (FileStream stream = new FileStream(@"c:\storage\" + filename + ".dump", FileMode.Create))
{
   formatter.Serialize(stream, myClass);
}
PostMessage(_window, MSG_SENDING_OBJECT, IntPtr.Zero, new IntPtr(int.Parse(filename)));

在 WndProc 中接收时:

if (msg == MSG_SENDING_OBJECT)
{
    IFormatter formatter = new BinaryFormatter();
    MyClass myClass;
    using (FileStream stream = new FileStream(@"c:\storage\" + lParam.ToInt32().ToString() + ".dump", FileMode.Open))
    {
        myClass = (MyClass)formatter.Deserialize(stream);
    }
    File.Delete(@"c:\storage\" + lParam.ToInt32().ToString() + ".dump");
}

对不起,代码中的拼写错误,我正在写这个临时并且无法测试......

于 2011-06-28T15:23:24.773 回答