【问题标题】:send argument from one winform application to another and populate a textbox将参数从一个 winform 应用程序发送到另一个应用程序并填充文本框
【发布时间】:2014-02-07 23:25:18
【问题描述】:

我有 2 个独立的 Winforms 应用程序。 Form1 有一个文本框和一个按钮。当我单击按钮时,我想将 textbox.text 作为命令行参数传递给我的第二个应用程序,然后在 Form2 上填充另一个文本框。

我目前可以将参数从一个应用程序传递到另一个应用程序,但是,我不确定如何使用来自 Form1 的参数填充 Form2 中的文本框。

表格1:

    private void bMassCopy_Click(object sender, EventArgs e)
    {
        string shortcutName = string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Programs), "\\", "MassFileCopy", "\\", "MassFileCopy", ".appref-ms");
        Process.Start(shortcutName, " " + tHostname.Text.ToString());
    }

表格2:

    [STAThread]
    static void Main(string[] args)
    {

        try
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            formMain mainForm = new formMain();
            Application.Run(mainForm);

            if (args.Length > 0)
            {
                foreach (string str in args)
                {
                    mainForm.tWSID.Text = str;
                }
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {                


        }
    }

上面的代码很好地接受了参数,但是,应用程序加载并且文本框没有被填充。断点似乎表明 foreach 循环直到 Form2 关闭后才会运行,但我无法在 Form2 加载之前运行 foreach 循环,因为没有要与之交互的文本框。

有什么想法吗?

【问题讨论】:

    标签: c# .net winforms textbox


    【解决方案1】:

    您尝试填充文本框的代码仅在 Form2 关闭后运行,因为 Application.Run 是模态的,并且在关闭表单之前不会返回。
    但是,您可以更改 Form2 的构造函数以接受字符串作为参数

    public class Form2 : Form
    {
        public void Form2(string textFromOtherApp)
        {
             InitializeComponent();
    
             // Change the text only after the InitializeComponent
             tWSID.Text = textFromOtherApp;
        }
    }
    

    并从 Main 方法中传递它

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    string initValue = (args != null && args.Length > 0 ? args[0] : string.Empty);
    formMain mainForm = new formMain(initValue);
    Application.Run(mainForm);
    

    【讨论】:

    • 这个解决方案工作得很好而且花花公子!我没想过只通过 mainForm obj 传递参数。
    【解决方案2】:

    您可以像这样处理表单的 Load 事件并填充 TextBox:

    private void formMain_Load(object sender, EventArgs e)
    {
        if (Environment.GetCommandLineArgs().Length > 1)
        {
            // The first command line argument is the application path
            // The second command line argument is the first argument passed to the application
            tWSID.Text = Environment.GetCommandLineArgs()[1];
        }
    }
    

    命令行参数中的第一个参数是表单应用程序的名称,因此我们在上面的代码中使用第二个命令行参数 - 即将 1 传递给索引器。

    【讨论】:

    • 刚刚测试了这个解决方案,它似乎也能按预期工作。非常感谢!
    猜你喜欢
    • 2014-11-01
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    • 1970-01-01
    • 2017-01-30
    相关资源
    最近更新 更多