当前位置: 移动技术网 > IT编程>开发语言>c# > C#隐藏主窗口的方法小结

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例总结了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#相关内容感兴趣的读者可查看本站专题:《c#数据结构与算法教程》、《c#常见控件用法教程》、《c#面向对象程序设计入门教程》及《c#程序设计之线程使用技巧总结

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网