C# Windows Messages in Console Application?

1.1k views Asked by At

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?

2

There are 2 answers

2
Yamamotooko On BEST ANSWER

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");
0
mm8 On

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.