好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#隐藏主窗口的方法小结

本文实例总结了C#隐藏主窗口的方法。分享给大家供大家参考,具体如下:

要求在程序启动的时候主窗口隐藏,只在系统托盘里显示一个图标。一直以来采用的方法都是设置窗口的ShowInTaskBar=false, WindowState=Minimized。但是偶然发现尽管这样的方法可以使主窗口隐藏不见,但是在用Alt+Tab的时候却可以看见这个程序的图标并把这个窗口显示出来。因此这种方法其实并不能满足要求。

方法一: 重写setVisibleCore方法

?

protected override void SetVisibleCore( bool )

{

    base .SetVisibleCore( false );

}

这个方法比较简单,但是使用了这个方法后主窗口就再也不能被显示出来,而且在退出程序的时候也必须调用Application.Exit方法而不是Close方法。这样的话就要考虑一下,要把主窗口的很多功能放到其他的地方去。

方法二: 不创建主窗口,直接创建NotifyIcon和ContextMenu组件
这种方法比较麻烦,很多代码都必须手工写

?

static void Main()

{

   Application.EnableVisualStyles();

   Application.SetCompatibleTextRenderingDefault( false );

   System.Resources.ResourceManager resources =

     new System.Resources.ResourceManager( "myResource" , System.Reflection.Assembly.GetExecutingAssembly());

   NotifyIcon ni = new NotifyIcon();

   ni.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Warning;

   ni.BalloonTipText = "test!" ;

   ni.BalloonTipTitle = "test." ;

   //ni.ContextMenuStrip = contextMenu;

   ni.Icon = ((System.Drawing.Icon)(resources.GetObject( "ni.Icon" )));

   ni.Text = "Test" ;

   ni.Visible = true ;

   ni.MouseClick += delegate ( object sender, MouseEventArgs e)

   {

     ni.ShowBalloonTip(0);

   };

   Application.Run();

}

如果需要的组件太多,这个方法就很繁琐,因此只是做为一种可行性研究。

方法三:前面两种方法都有一个问题,主窗口不能再显示出来。现在这种方法就没有这个问题了

?

private bool windowCreate= true ;

...

protected override void OnActivated(EventArgs e)

{

   if (windowCreate)

   {

     base .Visible = false ;

     windowCreate = false ;

   }

   base .OnActivated(e);

}

private void notifyIcon1_DoubleClick( object sender, EventArgs e)

{

   if ( this .Visible == true )

   {

     this .Hide();

     this .ShowInTaskbar = false ;

   }

   else

   {

     this .Visible = true ;

     this .ShowInTaskbar = true ;

     this .WindowState = FormWindowState.Normal;

     //this.Show();

     this .BringToFront();

   }

}

希望本文所述对大家C#程序设计有所帮助。

dy("nrwz");

查看更多关于C#隐藏主窗口的方法小结的详细内容...

  阅读:74次