How to send object instances to WndProc

ぐ巨炮叔叔 提交于 2019-12-13 04:02:52

问题


I'm using my custom class that describes some states and values:

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

Because of application architecture, for forms interaction is used messages and its infrastructure (SendMessage/PostMessage, WndProc). The question is - how, using SendMessage/PostMessage, to send an instance of MyClass to WndProc? In my code PostMessage is defined next way:

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

So, I need that below my custom message number somehow to send and an MyClass instance, so in WndProc I could use it for logics needs. It's possible?


回答1:


You won't be able to do that. Pointers in a managed language mean nothing, they are often relocated and killed when no longer referenced. Well maybe you would be able to achieve something that kinda works this way (in process), with unsafe code and pinned pointers but that will be your doom.

If you want only inprocess communication then beware of cross thread communication implications.

If you need cross process communication see this thread: IPC Mechanisms in C# - Usage and Best Practices

Edit:

Sending uniqueID through SendMessage to fetch serialized object. I don't advise to to this since it is hacking and bug prone but you requested:

when sending the message:

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)));

when receiving in 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");
}

Sorry for typos in the code, I'm writing this ad hoc and cannot test...



来源:https://stackoverflow.com/questions/6508622/how-to-send-object-instances-to-wndproc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!