'C# Windows Messages in Console Application?

I need to use IPC to receive messages from another process. Currently I am using WPF application to receive messages using WindowsMessages but I am wondering if that communication would work in a ConsoleApp instead? At first glance I've noticed that HwndSource cannot be found in ConsoleApp so the question is if there is a way to receive WindowsMessages in a ConsoleApp (preferred way) or if it would be easier to create a WPF app instead?



Solution 1:[1]

You could use a walkaround (agree, not the nicest and cleanest way but worked for me). Add a reference to System.Windows.Forms and create a class that derives from Form as follows:

public class ConsoleReceiver : Form
{
    public ConsoleReceiver()
    {
        SetFormProperties();
    }

    private void SetFormProperties()
    {
        Text = "YourWindowName";
        Width = 0;
        Height = 0;
        ShowIcon = false;
        ShowInTaskbar = false;
        Opacity = 0.0;
        Visible = false;
        ControlBox = false;
        MaximizeBox = false;
        MinimizeBox = false;
        FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
    }

    protected override void WndProc(ref Message m)
    {
        //Wait for your message here
        Console.WriteLine($"Window message received {m.Msg} {m.LParam} {m.WParam}");
        base.WndProc(ref m);
    }
}

Above code will create an invisible form window which you will be able to find by name and send you window messages to.

In the Main method of your console app Create a message loop and initialize your form:

static void Main(string[] args)
    {
        Application.Run(new ConsoleReceiver());
    }

Lastly, within your sender app find the window by name and once it is found you will be able to send your window messages.

Declare the method:

[DllImport("user32.dll")]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

And use it as follows:

FindWindow(null, "YourWindowName");

Solution 2:[2]

The SendMessage and PostThreadMessage APIs will only work when there is an active message loop running in the receiving application.

If you want to communicate with a console app on the same machine, you could use named pipes. There is an example available in the documentation that should be helpful.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yamamotooko
Solution 2 mm8