How can I prevent a user from closing my C# application?
Asked Answered
L

4

4

How to make unclosed application in C#? I want to disable the 'X' button of the form and prevent the Windows Task Manager from closing it as well.

I know that one way to prevent a form from closing is to handle the FormClosing event, but how do I prevent the task manager from closing it?

Limiter answered 11/1, 2011 at 8:58 Comment(7)
You can't prevent them from killing the application process in Task Manager, and why would you want that? An alternative is to have a listening process that restarts your application when it gets killed, but that is the fast track to annoyed users and no application adoption. For the record, I wouldn't use an application that behaved like that.Spare
@Adam of course you can if your program has admin privileges. It's not even that hard to do. For example you could simply hook the APIs taskmanager uses to either enumerate or kill the process. I wouldn't use C# for that though since it'd need to load the whole CLR in the target process. But I see no legitimate use of that.Drafty
@Tvm Can you give one reason why you'd want to do that? That behavior sounds pretty malware-ish.Drafty
@CodeInChaos fair enough, but Microsoft don't even stop you from killing system processes, so if I installed an application that prevented me from doing what I wanted on the system I'd be firing up add/remove almost instantly. A relevant link: blogs.msdn.com/b/oldnewthing/archive/2004/02/16/73780.aspxSpare
@Adam I doubt that a program that's so misbehaved that it interferes with the taskmanager will add itself to add/remove. It'll most likely place itself under a strange name somewhere in the windows directory.Drafty
@CodeInChaos either way, it wouldn't last long on the machine.Spare
@CodeInChaos, see my answer. It contains a few examples of why one might want to make it difficult to for a user to close an application and not be malware.Tyrontyrone
A
24

No, it is not possible to prevent Task Manager from closing your application. Task Manager can forcibly terminate a process that is not responding; it doesn't need the application's permission to close it, and it doesn't ask nicely, either. (See this answer for more on Task Manager, and a comparison between the different ways that an application can be closed.)

The only conceivable workaround is to have two processes, each of them configured to detect when the other one is closed and start up a new instance. Of course, this still won't stop one of the processes from being killed, it will just allow you to restart it. And this probably falls into the category of user-hostile behavior. If I've resorted to using the Task Manager to close your app, I probably want it gone, no matter what you as the programmer intended. And I'm guaranteed to be mad if it keeps spinning up new processes (also likely to be mad is my virus scanner, because it's seen this kind of behavior before).

I recommend that you reconsider your application's design. If you need something that runs all the time in the background, you should be creating a Windows Service. Of course, services don't have a user interface, and it appears that your application requires one. So better yet, write your code defensively: Save the application's state so that it can be closed and restored at will. You have to handle the case where the computer is shutting down anyway, so how hard is it to handle just your app being shut down?

As Microsoft's Raymond Chen would tell you, Windows doesn't have a mechanism for this because no one could have imagined an app as awesome as yours that no user would ever want to close.


As far as disabling your form's close box, the close icon in the system/window menu, and the Alt+F4 keystroke, this is relatively straightforward. You'll need to override your form's CreateParams property, and set the CS_NOCLOSE window class style:

protected override CreateParams CreateParams
{
   get
   {
      const int CS_NOCLOSE = 0x200;

      CreateParams cp = base.CreateParams;
      cp.ClassStyle |= CS_NOCLOSE;
      return cp;
   }
}

Compile and run. You'll get a form that looks like this (note the disabled close button on the titlebar and the absence of a "Close" menu item in the system/window menu):

     Form with CS_NOCLOSE style

Note that when doing this, you should really provide an alternative mechanism within your application's interface to close the form. For example, on the "master" form from which this dialog was displayed.

Aniela answered 11/1, 2011 at 9:16 Comment(3)
@Tvm Murthy: Sure, it's a useful trick and can come in handy. I prefer it to just throwing e.Cancel = true or something into the FormClosing event, because this gives the user a visual indication that they cannot close the form that way. Of course, handling FormClosing makes more sense if you just want to get confirmation from the user that they actually did intend to close the app.Aniela
I can conceive plenty of other workarounds. But I see no reason why a legitimate program would ever prevent the taskmanager from closing it.Drafty
@CodesInChaos, I can see several examples, the most obvious of which is an antivirus program. Task Manager is not the only program capable of calling for process termination. Another example: I have a Windows Service monitoring machines that are shared by multiple users, some of whom are being irresponsible with them. They need administrative access so I can't prevent them from reaching Task Manager, but I need to prevent them closing the monitoring app.Sharlasharleen
D
9

You should never do things like this, but if you really need this you should create a service.

Dunton answered 11/1, 2011 at 9:1 Comment(5)
This answer is useless. A Windows service can be killed through the task manager just like anything else. The opinion that it should never be done is likewise unhelpful - there are some situations, such as an antivirus or a monitoring app on shared computers, where such a setup is necessary. Stating that it should never be done is incorrect.Sharlasharleen
You can manage the service that user will not be able to stop it. You can do this with process as well but service is more appropriate IMHO. Regarding that unhelpful opinion. The application should not manage the way it is executed. This is role for system administrator.Ceram
"You can manage the service that user will not be able to stop it." How? If there is some magic way to prevent a user who can access the Task Manager from ending the service's process, I'm all ears. Regarding your opinion about application management, again you are not making sense. You seem to be assuming he is not a system administrator, and you also provide no information on how he can accomplish the task he asked about.Sharlasharleen
You have right that this is not the best answer in the world as it does not provide the solution, but IMHO the approach is invalid there fore this can be some sort of help. IF you think about user as SysAdm, there we do not have anything to discuss, a good SA will not approve any software that he can not manage. In case of system users, a SA create a group policy that define user can or can not close such application. This key competence distinction is crucial.Ceram
Why it is crucial ? Because even if developer will be able to catch all closing signals and prevent them to act for current system version. In next version system may came up with new solution of closing app. Then developer should rewrite his application as well. That is why the aspect of how application is manage in system is the administration thing not development. The shutdown hook, is valid when we want to inform and re-assure that he really want to stop the application but at the end of the day the decision is always up to him.Ceram
T
5

This isn't an answer to the question, but I think it might be important to point out that it is not always invalid to create an application that the user has to really go to great lengths to terminate. In the case of an internal private application which is designed to run on machines owned by a company and operated by employees of the company who use the app to do their work as employees, it would be perfectly legitimate to force the app to always stay running. @TvmMurthy question appears to be dealing with exactly this situation.

In my own work, MS Outlook is started up as one of my workstation's startup apps, and I leave it running all day, and into multiple days until I reboot the machine. I have also written Windows Form apps that keep me informed about the status of processes I am responsible to monitor on some of our servers. I wrote these apps to specifically stay running all the time, and only manifest themselves as popups when something is detected that I need to know about (they minimize to the toolbar to keep them out of the way). I use SharpReader for keeping up with my RSS feeds, and it is naturally designed to run constantly. It minimizes to the toolbar, even if you click the red X, and can only be terminated by a context menu from the toolbar or by use of the Task Manager -- and this is perfectly reasonable, even expected, given its function!

Devs should not make the assumption that all applications are voluntarily installed and used by users who are free to run whatever software they desire and when they desire to use it, or that their own preferences are what govern the industry or other users. It is Business Requirements that govern application behavior, not prejudices of developers. As a developer working in industry, I've been required to write lots of behaviors into software that I wouldn't have written had I been writing the software for myself.

Downvoting a question because you don't like what the user has been clearly directed to design into his or her application displays a kind of pettiness or closemindedness that is not particularly commendable. Upvoted question to counteract this.

Tyrontyrone answered 19/12, 2011 at 17:42 Comment(6)
In these scenarios, there are alternative mechanisms to prevent the application from being closed that function external to your application. For example, you can set the application to replace Explorer as the default shell. Or you can set up Group Policies to prevent user without appropriate privileges from closing the application. None of these things can or should be done from within the application's code.Aniela
This answer misses the point of what people are saying. It's not just a matter of "this requirement is bad because it offends my sensibilities", it's "this requirement is bad because it's impossible, and it's designed to be impossible because the operating system has a different mechanism to achieve what you want". In this case that's Group Policies, as Cody Gray says.Tiberius
@BenAaronson - I'm not missing any points. And my sensibilities are not being offended. I am simply pointing out facts of life. Cody Gray's comment is completely valid, and I am not disputing it, except that it is his opinion that certain things cannot be or should not be done from within the application's code. In my humble opinion. You're free to disagree of course, and I am sure you do. Isn't diversity wonderful?Tyrontyrone
@Tyrontyrone I didn't mean your sensibilities were being offended. I don't know how you read it that way. I'm also not sure how it's a matter of opinion whether something can or cannot be done.Tiberius
@BenAaronson Sorry, I guess my reading comprehension level isn't quite up to snuff. Or maybe I'm being too sensitive! "Can" implies "ability". Can I code something that does "X"? That's not a matter of opinion. "Should" implies questionability. Should I code something that does X? That's definitely opinion. I can code something that will fight tooth and nail to avoid being uninstalled, but should I do so? Usually not! I was simply chiming in with an "edge case" -- that in some odd cases, it might be acceptable to create an application that is hard to uninstall. That's all.Tyrontyrone
@Tyrontyrone Sure, I understand. And I do agree with your ultimate point- thinking that a requirement is "bad" isn't a reason to judge a question to be bad. Either there could be some reason for the requirement you're not aware of, or it could a developer working towards requirements he's given and has no control over. I just don't think this question is a good example of that point, because once you say your requirement is to prevent killing a process through the task manager, you're no longer on bad requirements that you shouldn't do, but impossible requirements that you can't do.Tiberius
U
0

It is not that hard to protect a process from beeing killed by regular users. An application can modify it's own process ACL preventing ANY taskmanager to kill it. They will simply get an "Access denied!" when trying to kill the process.

You should, however, allways allow administrators to be able to kill the process so it wont interfere with a system shutdown or other administrative tasks.

I could provide you with code, if still nescessary.

Unpopular answered 1/10, 2015 at 15:16 Comment(3)
Please provide the code to help future readers of thisCosignatory
csharptest.net/1043/…Unpopular
Please edit your answer to include any changes and links. Remember, any link should have the necessary code and explanations from that link in order to answer the question without clicking on the link. (Additionally you have supplied a non-HTTPs link, which will not help, it appears the HTTPs cert has expired)Cosignatory

© 2022 - 2024 — McMap. All rights reserved.