I'm using my custom class that describes some states an开发者_开发技巧d 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?
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...
精彩评论