我有一个使用Application.Run
运行的表单1。
我想隐藏这个表单(我需要它隐藏,因为我在后台运行一些东西,所以它们必须执行),并打开另一个用于登录的表单。
我的尝试是在我的表单1构造函数中执行命令this.Hide();
,如果登录成功,则显示我的表单1,但似乎不起作用。有任何想法吗?
只需重写OnVisibleChanged方法并在其中更改窗体的可见性,类似于以下内容:
protected override void OnVisibleChanged(EventArgs e)
{
base.OnVisibleChanged(e);
this.Visible = false;
}
就是这样!简单而干净。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
protected override void SetVisibleCore(bool value)
{
// Quick and dirty to keep the main window invisible
// you can put some logic here to decide when to use the
// incomming value and when to force it to be false as I
// am showing here.
base.SetVisibleCore(false);
}
}
using System;
using System.Windows.Forms;
namespace HideMainWinForm
{
public partial class Form1 : Form
{
// Initially the main form cannot show
private bool _canShow = false;
public Form1()
{
InitializeComponent();
Form2 frm = new Form2();
frm.FormClosed += new FormClosedEventHandler(frm_FormClosed);
frm.Show();
}
void frm_FormClosed(object sender, FormClosedEventArgs e)
{
// Once Form2 is closed we now allow the main form to
// become visible.
_canShow = true;
this.Show();
}
protected override void SetVisibleCore(bool value)
{
base.SetVisibleCore(_canShow && value);
}
}
}
如果您需要在显示表单之前进行一些后台工作,我建议有两种可能的选择。
第一种方法是,在创建表单并调用Application.Run
之前,简单地执行您的后台工作。
第二种选择是,如果您需要在执行后台工作时保持消息循环处于活动状态,则可以使用不带From参数的Application.Run
重载,并在您想要的时间准确地显示您的表单。唯一的问题是,当您想要结束应用程序时(因为它没有一个可以观察其关闭事件的表单),您将不得不手动调用Application.Exit
或Application.ExitThread
。
因此,您的代码可能如下所示:
void Main()
{
// trigger some background work
...
// and start the message pump
Application.Run();
}
void SomeBackgroundWork()
{
// let's say now you completed the background work and you want to show your main Form
MyForm f = new MyForm();
f.Close += delegate { Application.Exit(); };
f.Show();
}
this.Hide()
实际上设置了this.Visible = false
,但是在窗体实例化后立即调用form.Show
(由Application.Run
调用),并且form.Show
内部设置了this.Visible = true
(当然与Hide相反...)。private bool firstShow = true;
protected override void OnShown(EventArgs e)
{
if (firstShow)
{
this.Hide();
firstShow = false;
return;
}
base.OnShown(e);
}
表单将会出现一瞬间,然后立即消失。
布尔标志firstShow
允许您仅在第一次调用Show()
时隐藏表单,而对于以下的调用,它将像平常一样工作。
Windows Forms有一个非常适合此类问题的事件,称为Form.Shown
。每个Form对象仅在首次显示时调用一次。基本上这就是digEmAll的答案,但已经内置了。
在构造函数中添加一个由Form1.Shown
调用的事件处理程序,然后在处理程序中调用Hide()
。
public form1()
{
InitializeComponent()
this.Shown += new EventHandler(form1_Shown);
// call splash page
}
void form1_Shown(object sender, EventArgs e)
{
this.Hide()
}
protected override void OnVisibleChanged(EventArgs e){
base.OnVisibleChanged(e);
this.Visible = false;
}
使用(await和async)的方法必须在形式初始化中包含(result)这个单词。
例如:
public frmForm1() {
InitializeComponent();
try {
if (Program.LaunchedViaStartup == true) {
var varclsReturnBack = funcStartBackGroundObjectsAsync().Result;
}
} catch (Exception varException) {
Console.Write(varException.Message);
}
}
this.Hide()
对我起作用,我们需要一个能重现问题的代码示例... - digEmAll