[英]C# from winform application how to open another winform application and send value to it?
我有 2 個 winform 應用程序,比如form1
和form2
。
它們通過單獨的視覺工作室程序進行編程
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.