I need it for their own exit button. Tell me please?
I try this:
this.Close(); //or Exit dont work(
You can use the CoreApplication class. It provides a static exit method:
public void CloseApp()
{
CoreApplication.Exit();
}
However, the documentation states the following:
Note Do not use this method to shut down an app outside of testing or debugging scenarios.
Sadly, the reason behind that is left unkown.
Further more, you can use the old-fashioned Application.Exit method (non-static):
public void CloseApp()
{
Application.Current.Exit();
}
Here you should also take a look in the remarks:
Use this method to provide UI that enables users to exit your app. Normally, however, you should not provide this UI because the system automatically manages app lifetime and terminates suspended apps as needed to free resources.
tl;dr:
Both Exit methods will terminate the app, rather than suspending it. You should ask yourself if this really is the action you want to do.
This is the supported way of exiting a UWP app:
Application.Current.Exit();
It is however relatively rare that you should use it. Consider carefully the UI experience related to the scenario where you would use this method. For example it may be justified to programmatically exit an application if some account has expired or security permissions managed remotely were revoked. It is rare that you have your own "Exit" button sitting in the middle of your screen without contravening Windows guidelines.
If you want to suspend the app instead of terminating try to use ApplicationView.TryConsolidateAsync(). For example, if app implements only one ApplicationView try calling ApplicationView.GetForCurrentView().TryConsolidateAsync() to close the app.
The obvious benefit of this method is app is closed just as you will do by pressing close button in titlebar, the closing is graceful, animation is the same and app is suspended instead of abruptly exiting.
Also, when you launch your app again after closing by this method, app starts in the same position and size as you closed it before while using Application.Current.Exit() and CoreApplication.Exit() doesn't start the app in the same position and size.
Related
I have a c# form application. when this form is closed from task-manager's process i have to do something in my Form application. is it possible?
I apologies if i mislead anything. but i need this solution.
No you can not. What you can do, in order to track this kind of situation, is on startup create some hidden file in directory where you guaranteed by the OS for write permit and on the close of your application, delete that file.
In this way, if on startup of your app, you will find hidden file, that will mean that application was closed non in normal way. So you can execute some actions accordingly.
Hope this helps.
The task manager will try to close your application gracefully first. You will get a normal close signal that you can act on. In a Forms Application that probably corresponds to the OnClose/Closing of the main window. If this signal is not used to end the application in time, the task manager will kill the process. You will not be able to intercept that or act upon it.
Based on what I know, Killing a process with Task Manager is immediate.
The application is not able to get informed in any way.
Task manager generally call the Windows API ExitProcess to kill the process.
On how to hook API, you can refer to:
http://www.codeproject.com/KB/system/hooksys.aspx
SOURCE
In alternatve, you could create an additional process which obsverve the main application and if he find that the application is closed then do something. If the main application is closed normally, then the process is killed from the main application. thiS could be an easy workaround.
"No you can't, what you can do though is do something just before the form is disposed. msdn.microsoft.com/en-us/library/…. What exactly are you trying to archieve? –"
UPDATE
Based on your response to my comment:
What if you do something else. Create a windows service (daemon) that checks when your form is open (windows name) and then monitors the form to check when it is closed, and when that happens it calls the web service you need.
Your windows service would be as simple as this:
Thread thread = new Thread(() =>
{
while (!formClosed)
{
if (!Process.GetProcesses().Any(x => x.MainWindow.Title.Contains(windowName)))
{
//form closed, call your web service
}
Thread.Sleep(5000);
}
});
I am writing an application in c# to lock or freeze all programs untill user enters a value in the app's textbox and clicks ok.
The purpose of the app would be to get people to enter their time.
As far as I know you can set it to top most but they can end the app with task manager so am stuck here..
formName.TopMost = true;
Any help would be appreciated
Yes, that's correct. The Windows operating system allows multiple programs to run at one time. What you're experiencing is entirely by design.
If I remember correctly, the TopMost property applies only to windows in your process, and as you mention, it's all quite irrelevant: the user can still kill your application using the Task Manager.
There's no legitimate way of getting around that. It's not a "limitation", it's a feature. Any app that prevents itself from being closed by the Task Manager is treading dangerously closely on the category of software that we call malware. Nothing good can come out of pursuits like this.
Relevant reading: The arms race between programs and users
Perhaps a good compromise solution is to make your window/form actually top-most and disable the Close button so that the user knows they shouldn't try and close it. This is almost always enough to stop a user that is not determined to end your application by any means necessary, and that's about all you should ever be concerned with.
See the sample code here for how to make your window/form always appear on top of other running applications by setting the WS_EX_TOPMOST flag or toggling HWND_TOPMOST.
I've also already written a detailed answer here about disabling the Close button the correct way by setting the CS_NOCLOSE class style.
I have an application that imports data from Excel. However, when I run the winforms app and I intrupt the application, using System.Windows.Forms.Application.Exit(); I can still see the "MyAppName".vshost32.exe running in task manager.
When I exit the application in debug mode, the form closes, but the VS IDE is not "stopped".
How do I ensure the application ends correctly.
Your call to Application.Exit() is working fine. The MyAppName.vshost32.exe executable is a host for debugging purposes. It runs whilst you have a project open in Visual Studio, regardless of if there is an active debugging session.
Update: Ok, I misunderstood. The above is true, but you're probably having problems with hung threads in the background. You need to terminate your threads to make it close properly. Asher's answer covers this. If you're just trying to do a super-hacky quick-and-dirty kill, you can use the following (though I take no responsibility for side effects, since it's extremely hacky):
System.Diagnostics.Process.GetCurrentProcess().Kill();
The process doesn't terminate because it still has foreground threads running.
If you create threads in your application you need to mark them as background threads or make sure they terminate when you want the application to exit.
Have you tried the more brutal Environment.Exit() function?
Application.Exit() just sends a message saying to shutdown; if the message never gets processed (for whatever reason), the application will stay running indefinitely.
From the MSDN documentation of Application.Exit():
The Exit method stops all running message loops on all threads and closes all windows of the application. This method does not necessarily force the application to exit. The Exit method is typically called from within a message loop, and forces Run to return.
I had a similar problem caused by a third party tool that did not allow me to set the threads as Background. Polynomial had the right idea, but then syntax is like this:
System.Diagnostics.Process.GetCurrentProcess().Kill();
I am now developing an application on Windows Mobile 6.5 with .Net Compact Framework 3.5 using C#. There is a function in the program that I use it to update the location information periodically from server side, but if I keep running this computation, it would cost too much energe. For this reason, I want to run it in background and I try to use BackgroundWorker to do this and it works well.
The problem I have now is that I can't minimize the program so that I have to keep the main form of the program run in foreground even if it's not doing anything and this is very inconvinence for a user. However, when I close the program, the BackgroundWorker will also be closed.
Is there any method to keep the update process running (somewhere in memory or so) when I close the program? and then can restore the information when I restart the program?
How about creating a Service instead of a background worker?
If your Form closes, then Application.Run (probably called over in Program.Main) returns and the process' primary thread exits, causing the application to terminate.
The solution, then, is don't close the Form, simply Hide it. By default the "MinimizeBox" property for your Form should have been true and it should have an [X] in the upper right corner. Clicking this minimizes the Form and will not exit your application.
The other option in some cases is to not have a Form at all. The challenge here is that the CF doesn't have any Application.Run overload that doesn't accept in a Form (like the desktop framework does). The Smart Device Framework does provide one if you want to go that route.
I have not used the .NETCF 3.5. However in the previous version on .NETCF 1.0/2.0 I observed that even if you close the application using (X) button, it just goes to background but remain in the memory.
If that is the case with .NETCF 3.5 as well then I think you do not need to anything here. The background worked will be running even if you close the application.
I Hope this will help you.
What is the best and cleanest way to close a console application on windows mobile?
The application by default is invisible and you cannot see it in the running programs, which is great for running a background process, but sometimes the user might need to close it..
Exit Main. Seriously. If you need someone to be able to exit is manually, there needs to be some mechanism like a shell icon and menu or a program in the Programs folder of something. How else would the user even know it's running? Any one of those visual cues would then set a named system event, and inside your Console app you'd have something listening for the same event (likely a worker). When it gets set, you take the actions required to shut down.
How would a user be able to close it if the application is not visible in the UI?
That's a great question. I once spent a long time trying to figure this out. Of course, we are assuming you can not (easily) return from Main. The correct answer on the desktop is System.Environment.Exit; But that method is conveniently not supported on CF.
An apparent second option is Application.Exit. That is on CF, but only applies to WinForms, and is in fact not guaranteed to exit your application.
So, throw an unhandled exception. ;)
EDIT: To kill it programatically from another app, you can look at Process.GetProcessById, and Process.Kill. Both of these are available on CF. You will have to somehow let the "killer" app figure out the "victim"'s ID. More convenient methods like Process.GetProcessesByName are not available on CF.
This technique isn't that elegant, though, and there may be permissions issues.
You could also consider some kind of IPC (inter-process communication), perhaps one overviewed in this previous Windows Mobile answer.
I decided to to read a boolean (keep alive) in the config file and have another application set it to false when I want to exit.
Its not that responsive but at least I can exit cleanly..