简体   繁体   English

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

[英]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 . 我需要从控制台应用程序 打开数据并将其发送到Windows窗体 ,然后一旦完成窗体中的进程并关闭,就将结果数据发送回控制台应用程序

Currently I have implemented the part where I am opening up the form and sending data as shown below, 目前,我已经实现了打开表单并发送数据的部分,如下所示,

C# console C#控制台

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

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. 如果您的专家会提供一些示例代码段/示例/参考来实现此要求,那将是非常不错的。

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 : 这将是您的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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM