How do I launch .net windows forms application with no visible windows?

一笑奈何 提交于 2019-12-10 16:46:12

问题


I have a .net windows forms application that needs to open directly to the notify icon (system tray) with no visible windows. I realize that I can do this in the onshown event or something like it. But if I do that I get a flash of the window. How can I avoid that flash? I have tried modifying my Program.cs file to look like this:

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);

MainForm frm = new MainForm();
frm.Visible = false;
Application.Run(frm);

However this doesn't work either because Application.Run() makes the form visible. I am pretty sure there is an easy answer that I am missing. Any help is greatly appreciated.


回答1:


There's an overload for Application.Run() that takes in no parameters, and thus doesn't immediately show a form on application launch. Of course, you'll have to manage what causes the application to terminate yourself since there's no initial or 'main' form for it to monitor. So for example it'd be your notification icon, which I'm sure you'll be able to handle.




回答2:


If you don't need a main form at the time you start your application, here is a link to an article that describes how to create just a NotifyIcon.




回答3:


You can try setting WindowState on frm to Minimized along with ShowInTaskbar to false. Also, I'm no expert, but I think you should handle the visibility logic in the MainForm constructor.




回答4:


Maybe a bit hackish, but you can create a borderless Form (FormBorderStyle.None) and set it's TransparencyKey to it's BackColor, disable ShowInTaskbar, then give that form to Application.Run(). Voilà. :)




回答5:


Here's a code snippet from the initialization method of a form I have that does exactly that. The app runs in the tray and the window shows when the user double clicks the notify icon. I have methods that handle resizing, etc. that ensure the form will only be closed through a menu option.

public MainForm()
{
  ...code
  Resize += MainForm_Resize;
  notifyIcon.DoubleClick += NotifyIconDoubleClick;
  WindowState = FormWindowState.Minimized;
  Hide();
}
private void MainForm_Resize(object sender, EventArgs e)
{
  if (FormWindowState.Minimized == WindowState)
     Hide();
}

private void NotifyIconDoubleClick(object sender, EventArgs e)
{
   Show();
   try
   {
      WindowState = FormWindowState.Normal;
      ...more code for other stuff
    }catch(yadda yadda)
      ...code
    }
 }


来源:https://stackoverflow.com/questions/2978597/how-do-i-launch-net-windows-forms-application-with-no-visible-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!