Solved

sending a string to my app via PostMessage

Posted on 2010-11-23
5
763 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…
A company’s greatest vulnerability is their email. CEO fraud, ransomware and spear phishing attacks are the no1 threat to a company’s security. Cybercrime is responsible for the largest loss of money to companies today with losses projected to r…

929 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now