PostMessage cannot pass C # string

Here is my prototype:

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    public static extern bool PostMessage(int hhwnd, uint msg, IntPtr wparam, IntPtr lparam);

And here is how I use it:

PostMessage(HWND_BROADCAST, msg, Marshal.StringToHGlobalAuto("bob"), IntPtr.Zero);

In another thread, I can intercept this message, but when I try to return bob with:

string str = Marshal.PtrToStringAuto(m.WParam); // where m = the Message object

I do not get bob in str.

I think this should be due to the fact that I was referring to the string "bob" in one thread stack, and this link makes absolutely no sense in another thread stack. But if that is the case, are these wparam and lparam pointers really only used for messages being sent on the same thread?

Edit * Bugfix: By stream, I mean the process. This is the problem of passing a string between processes, not threads.

+3
source share
2 answers

HGLOBALs . 16. HWND_BROADCAST , , .

, , , , "bob" , .

+1

. , lParam , , . SendMessage, .

http://boycook.wordpress.com/2008/07/29/c-win32-messaging-with-sendmessage-and-wm_copydata/

, .:)

:

    public void SendMsg(string msg)
{
    MessageHelper msgHelper = new MessageHelper();
    int hWnd = msg.getWindowId(null, "The title of the form you want to send a message to");
    int result = msg.sendWindowsStringMessage(hWnd, 0, msg)
    //Or for an integer message
    result = msg.sendWindowsMessage(hWnd, MessageHelper.WM_USER, 123, 456);
}

//In your form window where you want to receive the message

protected override void WndProc(ref Message m)
{
    switch (m.Msg)
    {
        case MessageHelper.WM_USER:
            MessageBox.Show("Message recieved: " + m.WParam + " - " + m.LParam);
            break;
        case MessageHelper.WM_COPYDATA:
            MessageHelper.COPYDATASTRUCT mystr = new MessageHelper.COPYDATASTRUCT();
            Type mytype = mystr.GetType();
            mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
            MessageBox.Show(mystr.lpData);
            break;
    }
    base.WndProc(ref m);
}
0

Source: https://habr.com/ru/post/1728501/


All Articles