Hasitha Shan
Hasitha Shan

Reputation: 2980

Send data from windows form to console

I have a requirement to open and send data to a windows form from a console application and then once the process within the form is done and closed send the resulting data back to the console application.

Currently I have implemented the part where I am opening up the form and sending data as shown below,

C# console

private static void open_form()
{
   ......
   Application.EnableVisualStyles();
   Application.Run(new Form1(data));
   //I need to capture the data returned from the form when the process is done inside it
}        

C# form

string accNumVal = "";

public Form1(string accNum)
{
   accNumVal = accNum;
   InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
   accNumVal = accNumVal + 10;

   //return accNumVal from here back to the console
   this.Close();
}

I have been struggling with this issue for some time and I am kind of in a hurry. It would be really great if you experts would provde with some sample code segments/ examples / references to implement this requirement.

Upvotes: 1

Views: 2244

Answers (1)

Aelphaeis
Aelphaeis

Reputation: 2613

One way to do this is to create an event and to subscribe something to it. After this you can print it to console. Will add example in a bit.

In your case, you'd put the message in your Button click instead of your Load.

This would be your form

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    //This is your Event, Call this to send message
    public event EventHandler myEvent;

    private void Form1_Load(object sender, EventArgs e)
    {
         //How to call your Event
        if(myEvent != null)
            myEvent(this, new MyEventArgs() { Message = "Here is a Message" });
    }

}
//Your event Arguments to pass your message
public class MyEventArgs : EventArgs
{
    public String Message
    {
        get;
        set;
    }
}

This would be your Main :

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        //How to ensure that you'll get your message
        var myForm = new Form1();
        myForm.myEvent += myForm_myEvent;
        Application.Run(new Form1());
    }

    //What to do once you get your Message
    static void myForm_myEvent(object sender, EventArgs e)
    {
        var myEventArgs = (MyEventArgs)e;
        Console.WriteLine(myEventArgs.Message);
    }
}

Upvotes: 3

Related Questions