繁体   English   中英

来自winform应用程序的C#如何打开另一个winform应用程序并向它发送值?

[英]C# from winform application how to open another winform application and send value to it?

我有 2 个 winform 应用程序,比如form1form2

它们通过单独的视觉工作室程序进行编程

form1在 WindowsFormsApplication1.sln 中编程

form2在 WindowsFormsApplication2.sln 中编程

我想通过单击form1的按钮打开form2 (=WindowsFormApplication2.exe)

我在 WindowsFormApplication1.sln 中创建了一个方法

private void button3_Click(object sender, EventArgs e)    
{
     var p = new Process();
     p.StartInfo.FileName ="WindowsFormsApplication2.exe";
     p.StartInfo.Arguments = "10";
     p.Start();
}

此方法打开 WindowsFormApplication2.exe

然后我需要 WindowsFormApplication2 MessageBox 显示从 WindowsFormApplication1.exe 获得的值。 这清楚吗?

这应该很清楚......我无法解释得比这更简单


其他人通过评论或回答框回答的不是我想要的

如果我想将一个值从form1传递到同一个 .sln 中的form2 (也就是说,WindowsFormApplication1.sln 有 form1 和 form2),这很容易

我可以用

Form2 form2 = new Form2(textBox1.Text);    
form2.Show();

构造函数Form2

public Form2(string smth)    
{
     InitializeComponent();
     label1.Text = smth;
}

但这不是我想要的

我想一切都清楚了。 请告诉我如何解决问题

C# 程序有一个static void Main()方法,它是应用程序的入口点。 您应该在 winform2 项目的Program.cs文件中看到类似的内容:

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new Form1());
}

如果你想让你的 winform2 应用程序接受命令行参数,你可以从这个方法中捕获它们。 但首先你需要修改方法签名以接收一个string[]参数:

// Add a string[] argument to the Main entry point method
static void Main(string[] args)

现在,传递给此应用程序的任何命令行参数都将位于args数组中。

接下来,我们需要修改 winform2 应用程序的主窗体构造函数以接收一个或多个字符串参数,以便我们可以在Application.Run(new Form1())行中传递它们。

例如,您可以修改表单的构造函数以接收字符串(我以Form1为例):

public partial class Form1 : Form
{
    // Add a string argument to the form's constructor. 
    // If it's not empty, we'll use it for the form's title.
    public Form1(string input)
    {
        InitializeComponent();

        if (!string.IsNullOrEmpty(input)) this.Text = input;
     }
}

在我们启用表单接受字符串输入之后,我们现在修改对构造函数的调用以将字符串传递给我们的表单。 在这种情况下,我期待这样的字符串: /Title:"Some Form Title" ,因此我将查看args数组并尝试找到匹配项。

static void Main(string[] args)
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);

    // Try to find the 'Title' argument
    var titleArg = args?.FirstOrDefault(arg => arg.StartsWith("/Title:", 
        StringComparison.OrdinalIgnoreCase));

    // Now strip off the beginning part of the argument
    titleArg = titleArg?.Replace("/Title:", "");

    // And now we can pass this to our form constructor
    Application.Run(new Form1(titleArg));
}

现在您可以从命令行启动您的 WinForm 应用程序并传入一个字符串,该字符串将成为标题。 在这里,我从命令行运行.exe并传递/Title:"Custom Title From Command Line" ,但如果您以编程方式启动应用程序,则可以将此字符串分配给ProcessStartInfo实例的Arguments属性。:

在此处输入图片说明

暂无
暂无

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

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