1

Учебная задача. Нужно использовать именно сообщения.

Нужно сделать две программы, обменивающиеся данными через сообщения. Первая получает сообщение в духе "Start", после чего начинает каждые 5 секунд отправлять второму "Ask value". Второе в ответ шлёт "Send value" с какими-то данными.

Первая программа (проект WinForms):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace Oven_Monitor
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern int GetCurrentProcessId();

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint RegisterWindowMessage(string lpString);

        [DllImport("user32.dll")]
        public static extern IntPtr SendMessage(IntPtr hWnd, uint wMsg, UIntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll")]
        public static extern IntPtr PostMessage(IntPtr hWnd, uint wMsg, UIntPtr wParam, IntPtr lParam);


        private uint askMessageID      = RegisterWindowMessage("Ask value");
        private uint dataMessageID     = RegisterWindowMessage("Send value");
        private uint registerMessageID = RegisterWindowMessage("Register sensor");

        public Form1() {
            InitializeComponent();
            this.Text = "Really rare title";
        }

        public void checkSensors() {
            while (true) {
                PostMessage(secondAppHWnd, askMessageID, (UIntPtr)0, (IntPtr)0);
                System.Threading.Thread.Sleep(500);
            }
        }

        private IntPtr secondAppHWnd;

        protected override void WndProc(ref Message m) {
            if (m.Msg == registerMessageID) {
                secondAppHWnd = m.LParam;
                Thread tr = new Thread(checkSensors);
                tr.Start();
            } else if (m.Msg == dataMessageID) {
                //do some stuff
            }
            base.WndProc(ref m);
        }
    }
}

Вторая:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace HeatSensor
{
    public partial class HiddenForm : Form
    {
        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        public static extern IntPtr SendMessage(IntPtr hWnd, uint wMsg, UIntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern uint RegisterWindowMessage(string lpString);

        static private IntPtr mainAppHandle;

        public HiddenForm(IntPtr mainAppHWnd)
        {
            InitializeComponent();
            mainAppHandle = mainAppHWnd; //получаю извне
            string title = System.DateTime.Now.ToLongDateString();
            title += System.DateTime.Now.ToLongTimeString();
            title += System.DateTime.Now.Ticks.ToString();
            this.Text = title;
            this.CreateHandle();
            int currentWindowHandle = (int)FindWindow(null, title);
            SendMessage(mainAppHandle, RegisterWindowMessage("Register sensor"),
                (UIntPtr)0, currentWindowHandle);
        }

        private uint askMessageID = RegisterWindowMessage("Ask value");
        private uint dataMessageID = RegisterWindowMessage("Send value");
        private uint registerMessageID = RegisterWindowMessage("Register sensor");

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == askMessageID)
            {
                SendMessage(mainAppHandle, dataMessageID, (UIntPtr)1, (IntPtr)1);
            }
            base.WndProc(ref m);
        }
    }
}

checkSensors() отправляет сообщение и... вторая программа его не получает (HWnd и wMsg 100% правильные). Если взять эту строчку и вызвать из WndProc(), то всё будет работать как надо.

Что может быть не так?

Приведённый код полностью отражает проблемную часть программы и может быть скомпилирован.

1 ответ 1

1

Похоже, проблема в том, что я пытаюсь таким образом взаимодействовать с консольным приложением (либо следует сделать что-то ещё со скрытой формой).

В итоге, решил сделать 2 программу оконной и всё заработало. Осталось скрыть окно и запустить из него консоль.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.