1

I have a winforms app that is capable of showing forms, and even upon closing the last visible form will continue to run in the background - and I make use of a notify tray (system tray) icon to show that it is running.

I have code in place to prevent right click\Exit on this icon if any forms are visible. I check that

System.Windows.Forms.Application.OpenForms > 0

and while this seems to work for the most part, it may not be reliably (testing this application on other machines seems to yield unexpected results). Is there a way to check if a winforms app is running as a background process (as opposed to counting the number of open forms)?

Mani5556
  • 394
  • 2
  • 12
  • 33
  • 2
    It seems strange that you wouldn't _already_ know, via application state, whether you have any forms open or not - it sounds like this is an [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem), whereby actually you should be tracking what the user is doing and therefore already know what's open or not? – James Thorpe Apr 11 '16 at 15:51
  • It is most certainly an XY problem, but the solution to Y may be more reliable (and safer); I am already in the process of looking into what is going wrong with solution X, but in the meantime was mostly curious as to whether there was a more reliable way (i.e. am-I running in background or not). – Mani5556 Apr 11 '16 at 15:55
  • Just do this the other way around. Always cancel the close unless the user *explicitly* asked for the program to terminate. That just takes a bool variable. Review the use of the *allowClose* variable in [this snippet](http://stackoverflow.com/a/1732294/17034). – Hans Passant Apr 11 '16 at 16:14
  • @HansPassant I couldn't get it to work (it seems to just close every time regardless), but very good suggestion. – Mani5556 Apr 11 '16 at 16:28
  • I don't understand. Do you want it to continue to run in the background? Or do you want the application to end when all forms are closed? There is a class to do that but it might not be compatible with use of the [Taskbar Notification Area](https://msdn.microsoft.com/en-us/library/windows/desktop/dn742495(v=vs.85).aspx) but Microsoft would say that this is an inappropriate use of that. – Sam Hobbs Apr 11 '16 at 18:58
  • I want it to close ONLY if a.) the users right clicks on the system tray and goes to EXIT and ONLY allow close if there are no open forms (or it is, according to taskmgr, a background process that is sitting idle doing nothing, showing no forms) – Mani5556 Apr 11 '16 at 19:18

0 Answers0