• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 781
  • Last Modified:

sending a string to my app via PostMessage

Hi experts

I'm new to this windows message stuff (I tried to adapt some examples from various sources)
what I tried to achieve was the following.
My winformapp takes some arguments like

[STAThread]
        static void Main(string[] args)

whenever I call the exe with arguments, I need to call send some text to the already running app (see code snippets, one shows the main-method, one the COPYDATASTRUCT and the WinAPI and the last the overwritten WinProc Method)

My problem is that nothing happens. No exception, no messagebox showing, just absolutely nothing.

Do you have an idea what might be wrong?
public static class WinAPI
    {
        [DllImport("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
        [DllImport("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, ref COPYDATASTRUCT lParam);
        public const int HWND_MESSAGE = 0xffff;
        public const int WM_APP = 0x8000;
        public const int WM_COPYDATA = 0x004A;

        public static IntPtr FindWindow(string ProcName)
        {
            
            Process[] processes = Process.GetProcessesByName(ProcName);

            foreach(Process p in processes)
            {
                return p.MainWindowHandle;
            }

            return new IntPtr();
        }
    }

    public struct COPYDATASTRUCT
    {
        public IntPtr dwData;
        public int cbData;
        [MarshalAs(UnmanagedType.LPStr)]
        public string lpData;
    }

Open in new window

protected override void WndProc(ref Message m)
        {
            if(m.Msg == WinAPI.WM_APP)
            {
                this.ShowForm();
                
                
            }
            else if(m.Msg == WinAPI.WM_COPYDATA)
            {
                COPYDATASTRUCT mystr = new COPYDATASTRUCT();
                Type mytype = mystr.GetType();
                mystr = (COPYDATASTRUCT)m.GetLParam(mytype);
                MessageBox.Show(mystr.lpData);
            }

            base.WndProc(ref m);
        }

Open in new window

[STAThread]
        static void Main(string[] args)
        {
            //Single-Instance-App
            bool createdNew = true;

            Mutex mutex = new Mutex(true, "KrIksTasks2", out createdNew);

            if(createdNew)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new KrIksTasks());
                mutex.ReleaseMutex();
            }
            else
            {
                COPYDATASTRUCT cds;
                string test = "gugus";
                byte[] b = System.Text.Encoding.Default.GetBytes(test);
                cds.dwData = (IntPtr)100;
                cds.cbData = b.Length + 1;
                cds.lpData = test;

                IntPtr hwnd = WinAPI.FindWindow("KrIksTasks2");
                
                if(hwnd != IntPtr.Zero)
                {
                    WinAPI.SendMessage(hwnd, WinAPI.WM_APP, IntPtr.Zero, IntPtr.Zero);
                    WinAPI.SendMessage(hwnd, WinAPI.WM_COPYDATA, IntPtr.Zero, ref cds);
                }
            }
            
        }

Open in new window

0
Arikael
Asked:
Arikael
1 Solution
 
graberCommented:
Arikael this seems to fit your bill
http://stackoverflow.com/questions/1325270/how-to-send-a-string-via-postmessage
This may be your post.  It seems so based on time stamps.  
0
 
ArikaelAuthor Commented:
Hi

This seems to be c(++) code.
I tried it with a new string, but nothing happened

Other ideas, what might be wrong?
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
You could try this approach instead:
http://www.codeproject.com/KB/cs/CSSIApp.aspx
0
 
ArikaelAuthor Commented:
thanks I'll have a look at it tomorrow (out of office at the moment) and revert back
0
 
nffvrxqgrcfqvvcCommented:
The best thing to do for WM_COPYDATA is to create your own structures then use Marshal.StructureToPointer() and Marshal.PointerToStructure(). You will also want to use the SendMessage() definition that uses IntPtr. The reason using this way is your code becomes more dynamic because you can simply define your structure in each application. The lpData member of COPYDATASTRUCT should be an allocated pointer to that structure so that you can Marshal it back to that specific structure on the receiver. There is another important part for the receiver for example the application that sends data using SendMessage() will always return zero if you want your sender to know it has sent the data with no problems then the receiver should indicate this by informing the sender it processed the message, by doing that when the sender uses SendMessage() it will return one instead of zero this allows you to know the receiver has received the data. When you need to send different structures you can use the wParam member of SendMessage() using some unique value member to let the receiver know which structure your sending.

I don't like C# .NET but here is a VB.NET example that may help you.
'// Receiver 


Imports System.Runtime.InteropServices

Public Class Form1

    Private Const WM_COPYDATA As Integer = &H4A

    <StructLayout(LayoutKind.Sequential)> _
    Private Structure CopyDataStruct
        Public dwData As IntPtr
        Public cbData As Integer
        Public lpData As IntPtr
    End Structure

    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
    Private Structure MyDataStruct
        Public Data As Integer
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=255)> Public TextData As String
    End Structure

    Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
        Dim mds As MyDataStruct = Nothing
        Dim cds As CopyDataStruct = Nothing
        If m.Msg = WM_COPYDATA Then
            cds = m.GetLParam(cds.GetType)
            Select Case m.WParam.ToInt32
                Case 100 '// MyDataStruct
                    mds = Marshal.PtrToStructure(cds.lpData, mds.GetType)
                    Debug.Print(mds.Data)
                    Debug.Print(mds.TextData)
            End Select
            '// Inform sender we got this message.
            m.Result = 1
            Return
        End If
        MyBase.WndProc(m)
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Debug.Print(Me.Handle)
    End Sub

End Class

Open in new window

'// Sender

Imports System.Runtime.InteropServices

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        CopyData.SendMyDataStruct(169412078, 100, 12345, "Hello World")
    End Sub
End Class

Public NotInheritable Class CopyData
    Private Sub New()
    End Sub
    Private Const WM_COPYDATA As Integer = &H4A
    <StructLayout(LayoutKind.Sequential)> _
    Private Structure CopyDataStruct
        Public dwData As IntPtr
        Public cbData As Integer
        Public lpData As IntPtr
    End Structure

    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
    Private Structure MyDataStruct
        Public Data As Integer
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=255)> Public TextData As String
    End Structure

    <DllImport("user32.dll", ExactSpelling:=False, SetLastError:=True, CharSet:=CharSet.Unicode)> _
    Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As UInt32, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
    End Function

    Public Shared Sub SendMyDataStruct(ByVal handle As IntPtr, ByVal uniqueId As IntPtr, ByVal data As Integer, ByVal szText As String)

        Dim cds As CopyDataStruct
        Dim mds As MyDataStruct

        Dim pcds As IntPtr = IntPtr.Zero
        Dim pmds As IntPtr = IntPtr.Zero

        mds.Data = data
        mds.TextData = szText
        pmds = Marshal.AllocHGlobal(Marshal.SizeOf(mds))
        Marshal.StructureToPtr(mds, pmds, True)

        cds.dwData = IntPtr.Zero
        cds.cbData = Marshal.SizeOf(mds)
        cds.lpData = pmds
        pcds = Marshal.AllocHGlobal(Marshal.SizeOf(cds))
        Marshal.StructureToPtr(cds, pcds, True)

        ' SendMessage() will return (TRUE) if the application processed
        '               the message see receiver code.
        Debug.Print(SendMessage(handle, WM_COPYDATA, uniqueId, pcds))

        Marshal.FreeHGlobal(pmds)
        Marshal.FreeHGlobal(pcds)

    End Sub
End Class

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now