以编程方式从另一个窗体打开窗体

我正在制作Windows窗体应用程序。 我有一张表格。 我想在单击按钮时从原始表单在运行时打开一个新表单 。 然后编程方式关闭这个新forms (2,3秒后),但是从gui主线程以外的线程中关闭。

  1. 任何人都可以指导我怎么做吗?
  2. 新表格是否会影响或阻碍原始主表格中发生的事情? (如果是,而不是如何阻止它?)

要使用按钮单击打开,请在按钮事件处理程序中添加以下代码

Form1 m = new Form1(); m.Show(); 

这里Form1是您要打开的表单的名称。

也可以使用关闭当前表格

 this.close(); 

我会这样做:

 Form2 frm2 = new Form2(); frm2.Show(); 

并关闭我将使用的当前表格

this.Hide(); 代替

 this.close(); 

查看这个Youtube频道链接以获得简单的启动教程,如果您是初学者,您可能会发现它很有帮助

您只需要使用Dispatcher从UI线程以外的线程执行图形操作。 我不认为这会影响主表单的行为。 这可能对您有所帮助: 从BackgroundWorker Thread访问UI控件

这是一个太老的问题,但回答收集知识。

我们有一个原始表格(主表格),带有一个按钮,用于显示新表格(第二表格)。

在此处输入图像描述

点击按钮的代码如下

  private void button1_Click(object sender, EventArgs e) { New_Form new_Form = new New_Form(); new_Form.Show(); } 

现在点击后,会显示新表格。 因为,您希望在2秒后隐藏,我们将向新表单设计器添加onload事件

 this.Load += new System.EventHandler(this.OnPageLoad); 

加载该表单时运行此OnPageLoad函数

NewForm.cs中

  public partial class New_Form : Form { private System.Windows.Forms.Timer formClosingTimer; public New_Form() { InitializeComponent(); } private void OnPageLoad(object sender, EventArgs e) { formClosingTimer = new System.Windows.Forms.Timer(); // Creating a new timer formClosingTimer.Tick += new EventHandler(CloseForm); // Defining tick event to invoke after a time period formClosingTimer.Interval = 2000; // Time Interval in miliseconds formClosingTimer.Start(); // Starting a timer } private void CloseForm(object sender, EventArgs e) { formClosingTimer.Stop(); // Stoping timer. If we dont stop, function will be triggered in regular intervals this.Close(); // Closing the current form } } 

在这个新forms中,计时器用于调用关闭该表单的方法。

这是新forms,在2秒后自动关闭,我们将能够在两种forms之间不受干扰的forms上操作。

在此处输入图像描述

据你所知,

form.close()将释放内存,我们永远不能再与该表单进行交互

form.hide()将隐藏表单,代码部分仍然可以在其中运行

有关计时器的更多详细信息,请参阅此链接, https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view = networkframe-4.7.2