2014-02-07 51 views
2

我有2個獨立的Winforms應用程序。 Form1有一個文本框和一個按鈕。當我點擊按鈕時,我想將textbox.text作爲命令行參數傳遞給我的第二個應用程序,然後在Form2上填充另一個文本框。將參數從一個winform應用程序發送到另一個應用程序並填充文本框

我目前可以將參數從一個應用程序傳遞給另一個,但是,我不確定如何使用Form1的參數填充Form2中的文本框。

Form1中:

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 
     {     


     } 
    } 

上面的代碼接受這些參數就好了,但是,應用程序加載和未填充文本框。一個斷點似乎表明,直到Form2關閉之後,foreach循環纔會運行,但我無法在Form2加載之前運行foreach循環,因爲沒有與之交互的文本框。

任何想法?

回答

1

您試圖填充文本框的代碼僅在關閉Form2後才運行,因爲Application.Run是模態的,直到窗體關閉才返回。
但是你可以改變你的窗體2的構造函數接受一個字符串作爲參數

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); 
+0

此解決方案工作得很好,很棒!我沒有考慮通過mainForm obj傳遞參數。 – Residualfail

0

您可以處理窗體的Load事件,並填充文本框像這樣:

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傳遞給索引器 - 在上面的代碼中。

+0

剛剛測試過這個解決方案,它也似乎按預期工作。非常感謝! – Residualfail

相關問題