我正在制作Windows窗体应用程序.我有一张表格.我想在单击按钮时从原始表单在运行时打开一个新表单.然后以编程方式关闭这个新表单(2,3秒后),但是从gui主线程以外的线程中关闭.
Amr*_*rma 36
要使用按钮单击打开,请在按钮事件处理程序中添加以下代码
Form1 m = new Form1();
m.Show();
Run Code Online (Sandbox Code Playgroud)
这里Form1是您要打开的表单的名称.
也可以使用关闭当前表格
this.close();
Run Code Online (Sandbox Code Playgroud)
Tac*_*cit 11
我会这样做:
Form2 frm2 = new Form2();
frm2.Show();
Run Code Online (Sandbox Code Playgroud)
并关闭我将使用的当前表格
this.Hide(); 代替
this.close();
Run Code Online (Sandbox Code Playgroud)
查看这个Youtube频道链接以获得简单的启动教程,如果您是初学者,您可能会发现它很有帮助
小智 5
这是一个古老的问题,但回答是为了收集知识。我们有一个带有按钮的原始表单来显示新表单。
按钮点击的代码如下
private void button1_Click(object sender, EventArgs e)
{
New_Form new_Form = new New_Form();
new_Form.Show();
}
Run Code Online (Sandbox Code Playgroud)
现在,当单击时,将显示新表单。因为,您想在 2 秒后隐藏我们正在向新的表单设计器添加一个 onload 事件
this.Load += new System.EventHandler(this.OnPageLoad);
Run Code Online (Sandbox Code Playgroud)
此OnPageLoad函数在加载该表单时运行
在NewForm.cs 中,
public partial class New_Form : Form
{
private Timer formClosingTimer;
private void OnPageLoad(object sender, EventArgs e)
{
formClosingTimer = new 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
}
}
Run Code Online (Sandbox Code Playgroud)
在这个新表单中,计时器用于调用关闭该表单的方法。
这是新的表单,它会在 2 秒后自动关闭,我们将能够在这两个表单之间没有干扰的情况下对这两个表单进行操作。
对于你的知识,
form.close()将释放内存,我们永远无法再次与该表单交互
form.hide()只会隐藏该表单,代码部分仍然可以在其中运行
有关计时器的更多详细信息,请参阅此链接,https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.7.2
小智 1
您只需要使用 Dispatcher 从 UI 线程以外的线程执行图形操作。我认为这不会影响主窗体的行为。这可能对您有帮助: Accessing UI Control from BackgroundWorker Thread