Cancelling OnFormClosing and task manager - c#

According to MSDN
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.onformclosing.aspx
I am trying to block a user from closing a form (except for windows shutting down).
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (e.CloseReason != CloseReason.WindowsShutDown)
{
e.Cancel = true;
wiggle();
}
base.OnFormClosing(e);
}
When closing from the task manager "End task" button, the window do not closes as expected but I get an error after a few seconds
How does windows determines if a program is responding or not !
All the form does is nothing...

Task Manager asked the program to close and it didn't. At least in WinXP, the Task Manager doesn't like that and pops up the "Not Responding" window after several seconds.
It is typically a bad design to try and prevent app closings, especially this way. The next tab on TaskMan will bypass any such checks.

Related

WPF forms crashed

Is there any way to catch the crashed form and reopen it again.
public static void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
}
Setting e.Handler to true should prevent the app from shutting down. You will then have to write some code to bring the window up again. There is no "reopen the crashed form" switch I am afraid. There is not even any notion of a "crashed form" as far as the event handler is concerned.
Please also note that keeping an application running like this will leave it in an undefined state. What you really should do is to catch the exception where it occurs and then use the Dispatcher_UnhandledException event handler as a last resort for logging any unhandled exception, perhaps displaying a user friendly message and finally shutting the application down.

Modal "Please Wait" dialogue box with possible UI in the background process

I have a long running process we'll call ProcessA so I want to put a "Please Wait..." type dialogue box to discourage the user from trying to interact with the application and ensure they don't get "Not Responding" type info / errors (e.g. offering the opportunity to End Process)
My first thought is to set up a Background Worker to do the job and display a modal dialogue box in the foreground, and close it when ProcessA completes. However, the problem is that ProcessA throws up its own dialogue box at the end and then does some printing.
So if the user clicks anywhere on the application, ProcessA's dialogue box will disappear behind the application's window.
So how can I display the "Please Wait", but also prevent interaction with the main application while not having it show up as "Not Responding" while ProcessA is running?
ProcessA runs from a DLL and I don't have access to its code. (So I can't simply close the "Please Wait" when it's ready to show its own dialogue box)
My eventual resolution was just to use a Modeless "Please Wait", not perfect but hopefully will be acceptable for now...
_pleaseWaitForm.Show();
_pleaseWaitForm.Refresh();
DisableProcessWindowsGhosting();
ProcessA(); // Long running process
_pleaseWaitForm.Close(); // or maybe should it be Dispose()?
Since ProcessA ties up the UI it prevents user interaction anyway, and DisableProcessWindowsGhosting() prevents the "Not Responding" message or the user from closing the application if they get impatient.
A little bit sloppy so I'm still open to a more elegant answer...
Here is a naive sample.
class MyForm : Form {
private void Form_Load() {
ThreadPool.QueueUserWorkItem(_=>{
Form frmDialog = new Form();
//Cross-thread InvokeRequired
this.BeginInvoke(new Action(()=>{
frmDialog.ShowDialog(this);
}));
// to do long-time work here
// Cross-thread InvokeRequired
this.Invoke(new Action(()=>{
frmDialog.Dispose();
// frmDialog.Close(); the Close method doesn't release the frmDialog, just make it invisible. (Memory leak !!!)
}));
}
}

Windows Phone Back KeyPress + MessageBox crashes the app without Selection

I have a strange issue overriding BackkeyPress Function in code behind, inside the function i have a simple message box to Go back or cancel navigation ( stay in current page ), when no choice is made (ok or cancel ) and Messagebox is open for long time, Application crashes, when i try to debug, no exception is thrown and App remains in the state unless OK or cancel is pressed , but on Normal run ( without debugger ) the crash is apparent.
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
string caption = "exit?";
string message = "Do you still want to exit?";
e.Cancel = MessageBoxResult.Cancel == MessageBox.Show(message, caption,
MessageBoxButton.OKCancel);
base.OnBackKeyPress(e);
}
http://msdn.microsoft.com/en-US/library/windowsphone/develop/jj206947(v=vs.105).aspx
In Windows Phone 8, if you call Show in
OnBackKeyPress(CancelEventArgs) or a handler for the BackKeyPress
event, the app will exit.
You can work around this by calling Show on a different thread, as
described in the following steps. Override BackKeyPress or create a
handler for the BackKeyPress event. Set the Cancel to true to cancel
the back key press action. Dispatch a method that shows the
MessageBox. If the user chooses to leave the app, call Terminate(),
otherwise, do nothing.
I found one more solution to this, so I thought it would be good if I posted it here. It's just a workaround though.
private async void PhoneApplicationPage_BackKeyPress (object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
await Task.Delay(100);
if (MessageBox.Show(msg, cap, MessageBoxButton.OKCancel) == MssageBoxResult.OK)
{
//somecode
}
}
Source
When using Terminate() - be aware that a number of app.xaml.cs rootFrame navigating events associated with normal exit won't trigger, neither the ApplicationClosing or your page's OnNavigatedFrom. So check if anything going on is important. You might tack it on before terminating...

Can't stop form closing when background worker is in progress

I have a form with a background worker in a c# winforms application (Visual Studio 2010, .net 4). When the background worker is busy I would like to warn the user aboout it when tries to close the form and cancel form closing. I'd like to handle it in form closing event by setting form close cancellation to true.
BUT it still closes the form!
Here is the code snippet I use:
private void FormDrivenDistance_FormClosing(object sender, FormClosingEventArgs e)
{
if (myBackgroundWorker.IsBusy)
{
Messenger.ShowCriticalMessage("Don't close, in progress!");
e.Cancel = true;
}
}
Where is the bug?!
Thanks in advance!
Are you sure that myBackgroundWorker.IsBusy returns true? Have you tried setting a break point inside the check to make sure it's being called?
Are you sure that the event is hooked up properly?
If those things are true, the bug would have to be in some other part of the code.
There may also be some other handler on FormClosing setting Cancel to false, but that's probably a less likely scenario.
What if you move e.Cancel before your message?
Note that if you're trying to prevent the race condition and stop the InvalidOperationException caused when the form closes before the worker completes, it doesn't 100% do so; you might close it in the interval between the completion itself (InProgress is now false) and the callback (OnWorkerCompleted). You still need to handle the exception either way.
Since you have to handle it either way, you may as well just let the user close the form. It's a nuisance for the user to have to wait for something to complete that they don't care about.

How to Disable Alt + F4 closing form?

What is the best way to disable Alt + F4 in a c# win form to prevent the user from closing the form?
I am using a form as a popup dialog to display a progress bar and I do not want the user to be able to close it.
This does the job:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
}
Edit: In response to pix0rs concern - yes you are correct that you will not be able to programatically close the app. However, you can simply remove the event handler for the form_closing event before closing the form:
this.FormClosing -= new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);
this.Close();
If you look at the value of FormClosingEventArgs e.CloseReason, it will tell you why the form is being closed. You can then decide what to do, the possible values are:
Member name - Description
None - The cause of the closure was not defined or could not be determined.
WindowsShutDown - The operating system is closing all applications before shutting down.
MdiFormClosing - The parent form of this multiple document interface (MDI) form is closing.
UserClosing - The user is closing the form through the user interface (UI), for example by clicking the Close button on the form window, selecting Close from the window's control menu, or pressing ALT+F4.
TaskManagerClosing - The Microsoft Windows Task Manager is closing the application.
FormOwnerClosing - The owner form is closing.
ApplicationExitCall - The Exit method of the Application class was invoked.
I believe this is the right way to do it:
protected override void OnFormClosing(FormClosingEventArgs e)
{
switch (e.CloseReason)
{
case CloseReason.UserClosing:
e.Cancel = true;
break;
}
base.OnFormClosing(e);
}
Note that it is considered bad form for an application to completely prevent itself from closing. You should check the event arguments for the Closing event to determine how and why your application was asked to close. If it is because of a Windows shutdown, you should not prevent the close from happening.
You could handle the FormClosing event and set FormClosingEventArgs.Cancel to true.
I am using a form as a popup dialog to display a progress bar and I do not want the user to be able to close it.
If the user is determined to close your app (and knowledgeable) enough to press alt+f4, they'll most likely also be knowledgeable enough to run task manager and kill your application instead.
At least with alt+f4 your app can do a graceful shutdown, rather than just making people kill it. From experience, people killing your app means corrupt config files, broken databases, half-finished tasks that you can't resume, and many other painful things.
At least prompt them with 'are you sure' rather than flat out preventing it.
This is a hack to disable Alt + F4.
private void test_FormClosing(object sender, FormClosingEventArgs e)
{
if (this.ModifierKeys == Keys.Alt || this.ModifierKeys == Keys.F4)
{
e.Cancel = true;
}
}
Subscribe FormClosing event
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = e.CloseReason == CloseReason.UserClosing;
}
Only one line in the method body.
This does the job:
bool myButtonWasClicked = false;
private void Exit_Click(object sender, EventArgs e)
{
myButtonWasClicked = true;
Application.Exit();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (myButtonWasClicked)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
Would FormClosing be called even when you're programatically closing the window? If so, you'd probably want to add some code to allow the form to be closed when you're finished with it (instead of always canceling the operation)
Hide close button on form by using the following in constructor of the form:
this.ControlBox = false;

Categories