Solved

sending a string to my app via PostMessage

Posted on 2010-11-23
5
764 Views
Last Modified: 2013-12-17
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
Comment
Question by:Arikael
5 Comments
 
LVL 2

Expert Comment

by:graber
ID: 34196121
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
 
LVL 3

Author Comment

by:Arikael
ID: 34196489
Hi

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

Other ideas, what might be wrong?
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 34198093
You could try this approach instead:
http://www.codeproject.com/KB/cs/CSSIApp.aspx
0
 
LVL 3

Author Comment

by:Arikael
ID: 34204293
thanks I'll have a look at it tomorrow (out of office at the moment) and revert back
0
 
LVL 29

Accepted Solution

by:
nffvrxqgrcfqvvc earned 400 total points
ID: 34205116
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

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
This tutorial gives a high-level tour of the interface of Marketo (a marketing automation tool to help businesses track and engage prospective customers and drive them to purchase). You will see the main areas including Marketing Activities, Design …

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question