Search code examples
c#interopsendmessagepostmessage

using SendMessageTimeout


I am trying to connect to a virtual assistant to get her to say the things my program gives as output.

msdn: http://msdn.microsoft.com/en-us/library/windows/desktop/ms644952(v=vs.85).aspx

Using sendmessage works, but blocks the rest of my program while she speaks.

Postmessage doesn't work, the messages don't arrive at the virtual assistant.

So I found SendMessageTimeout.

In code:

    [DllImport("User32.dll")]
    public static extern int SendMessageTimeout(IntPtr hWnd, uint Msg, IntPtr wParam, ref COPYDATASTRUCT lParam, uint fuFlags, uint timeout);

    public void Speak(string s)
    {
        string json = @"{
        ""debug""   : ""on"",
        ""version"" : ""1.0"",
        ""priority"": ""2"",
        ""type""    : ""interaction"",
        ""interaction"" : {
                    ""interactionID"" : ""Agenda"",
                    ""actionID""      : ""Agenda"",
                    ""string"" : """ + s + @"""
                 }
        }";

        IntPtr hWnd = FindWindow(null, windowAnne);
        byte[] sarr = Encoding.Default.GetBytes(json);
        COPYDATASTRUCT cds;
        cds.dwData = (IntPtr) 100;
        cds.lpData = json;
        cds.cbData = sarr.Length + 1;
        SendMessageTimeout(hWnd, WM_COPYDATA, IntPtr.Zero, ref cds, 0x0000, 500);
    }

the result here is that the virtual assistant speaks, but the program still blocks for the duration of the timeout and my debugger gives me a stackimbalance issue.

Does anyone have suggestions on how to keep the program running while the virtual assistant speaks?

The program gives back sentences on what you are doing, but also has a thread running which can give back certain alarms and reminders. So a program that's blocked every time the virtual assistant speaks is not useful.


Solution

  • Try executing your method in a seperate thread:

    Using threads and threading

    Of course, these days I use the async / await pattern instead of managing my own threads.

    Asynchronous programming with async and await