實(shí)現(xiàn)代碼及簡短解釋如下:
復(fù)制代碼代碼如下:
//隱藏窗體的方法1/5:不指定任何窗體為主窗體
//注意:通常,在一個程序中,關(guān)閉主窗體,就可以關(guān)閉應(yīng)用程序。
//但是在沒有主窗體中,不行。
//只能使用Application.Exit()才能關(guān)閉應(yīng)用程序。
//using可以保證Application結(jié)束前,關(guān)閉MyMainForm
using (new Form1())
{
Application.Run();
};
//Application.Run(new Form1());</p><p>//隱藏窗體的方法2/5:
//通過close()關(guān)閉主窗口同時可以關(guān)閉應(yīng)用程序
protected override CreateParams CreateParams
{
get
{
Hide();
return base.CreateParams;
}
}</p><p>//隱藏窗體的方法3/5:
//這種方法仍然不能用Close主窗口的方式來關(guān)閉應(yīng)用程序, 還得使用Application.Exit。
protected override void SetVisibleCore( bool value)
{
base.SetVisibleCore(false);
}</p><p>//注意:方法2和3 使用Show好像沒辦法調(diào)出主窗口,比較郁悶。</p><p>//隱藏窗體的方法4/5 part1/2: 推薦使用!!!</p><p>//ApplicationContext實(shí)質(zhì)上就是一個Application與主窗體之間的連接器,
//掌管著二者之間的互動關(guān)系。其中最主要的,就是負(fù)責(zé)在主窗體
//關(guān)閉時結(jié)束線程。既然如此,我們只要根據(jù)需要自定義一個ApplicationContext就可以了
internal class HideOnStartupApplicationContext : ApplicationContext
{
private Form mainFormInternal;</p><p> // 構(gòu)造函數(shù),主窗體被存儲在mainFormInternal
public HideOnStartupApplicationContext( Form mainForm)
{
this.mainFormInternal = mainForm;</p><p> this.mainFormInternal .Closed += new EventHandler(mainFormInternal_Closed);
}</p><p> // 當(dāng)主窗體被關(guān)閉時,退出應(yīng)用程序
void mainFormInternal_Closed(object sender, EventArgs e )
{
Application.Exit();
}
}
//在Main中作如下修改:
HideOnStartupApplicationContext context = new HideOnStartupApplicationContext( new Form1());
Application.Run(context );</p><p>//隱藏窗體的方法5/5: 推薦使用!??!
//在構(gòu)造函數(shù)中或者直接設(shè)置form屬性
this.ShowInTaskbar = false;
this.WindowState = FormWindowState.Minimized;
程序中配合notifyIcon 控件一起使用,效果很好!
以上代碼在VS2005下編譯通過。
以下是補(bǔ)充:
WinForm程序啟動時不顯示主窗體的實(shí)現(xiàn)方法
方法一:
工程文件Project1.dpr代碼如下:
復(fù)制代碼代碼如下:
program Project1;
uses
Forms,
Unit1 in 'Unit1.pas' {Form1};
{$R *.res}
begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
新聞熱點(diǎn)
疑難解答
圖片精選