将数据从Windows窗体发送到控制台

时间:2014-05-29 15:39:42

标签: c# winforms console

我需要控制台应用程序中打开并发送数据到Windows窗体,然后在表单中的进程完成并关闭后< / em> 将结果数据发送回控制台应用程序

目前我已经实现了我打开表单并发送数据的部分,如下所示,

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#表单

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();
}

我一直在努力解决这个问题,我有点匆忙。如果您的专家会提供一些示例代码段/示例/参考来实现此要求,那将是非常好的。

1 个答案:

答案 0 :(得分:2)

这样做的一种方法是创建一个事件并订阅它。在此之后,您可以将其打印到控制台。稍微添加一些例子。

在您的情况下,您可以将消息放入按钮单击而不是加载。

这将是您的表格

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;
    }
}

这将是你的主要:

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);
    }
}