Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

sending a string to my app via PostMessage

Posted on 2010-11-23
5
Medium Priority
?
771 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 86

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 1600 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

Nothing ever in the clear!

This technical paper will help you implement VMware’s VM encryption as well as implement Veeam encryption which together will achieve the nothing ever in the clear goal. If a bad guy steals VMs, backups or traffic they get nothing.

Question has a verified solution.

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

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…

730 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