Setting DialogResult only after ShowDialog() in WPF - wpf

I have a window that I sometimes open using Show() and sometimes using ShowDialog(). In the second case, the returned dialog result is important for me. But if I set the DialogResult after calling Show() I get an InvalidOperationException. Is there a way to find out which method was used to open the window and set or not the DialogResult accordingly? Or is there another way?
Of course I know I can catch and ignore the exception, but I don't like this solution.

Use System.Windows.Interop.ComponentDispatcher.IsThreadModal inside the window to determine if it runs on a modal thread or not.

If you look at set_DialogResult in Reflector, it checks _showingAsDialog to determine whether the dialog is modal. Unfortunately this is a private field.
Do you always construct a new instance of the window before calling Show()/ShowDialog(). If so, you could pass an argument to the constructor indicating how it is to be shown.

You can use the Form.Modal property to check the kind of usage.
In the case of using Form.Show() you have to use another way to let the caller know of any results of the Form.
Is there a reason to use both ways of showing the form?

How about just setting this.DialogResult = DialogResult.blah in the form closing event?

Related

Closing messagebox from modal dialog closes the dialog

I have a custom modal dialog from which I want to invoke a Messagebox on error.
However on closing the messagebox, the dialog also closes.
Is there a way to keep the dialog open and just close the messagebox?
This seems to be the same issue as the one mentioned here. I found a way to fix it and through it, probably proof that it is indeed a bug. My solution, as mentioned here:
A workaround on this is to add a handler for the FormClosing event of your form, so you can cancel it there.
It seems that the bug is somewhat detectable by checking FormClosingEventArgs.CloseReason. This is normally "UserClosing" on normal close (even programmatically with calling this.Close()), but with this bug it's set to "None", a value I would assume is some kind of default that should normally never be used.
private void form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.None)
{
e.Cancel = true;
return;
}
// any other OnClose code you may wish to execute.
}
[EDIT]
Sorry, the issue in the linked question was OP using form.DialogResult as temp variable for the result of a message box, and that caused the main form to close, so that is, in fact, not related. Use a temp variable for stuff like that, folks.
The most likely real cause of this is that the form's AcceptButton is set, and the actual accept button's code does validation. Even if the validation raises an error, AcceptButton will cause the form's DialogResult to be set to OK, which closes the form. To prevent this, either don't set the AcceptButton property and just set the DialogResult manually, or, on error, specifically clear the DialogResult by setting it to DialogResult.None.

Form closing immediately

Dim details As New frmDetails(ID, JobID, True)
details.ShowDialog()
The form flashes open and immediately closes. If I use Show() rather than ShowDialog() it stays open and look fine. Here are some things I've checked:
Breaking in FormClosing shows only
System.Windows.Forms.Form.OnFormClosing
System.Windows.Forms.Form.CheckCloseDialog
System.Windows.Forms.Application.ThreadContext.System.Windows.Forms.UnsafeNativeMethods.IMsoComponent.FContinueMessageLoop
System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop
System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner
System.Windows.Forms.Application.ThreadContext.RunMessageLoop
System.Windows.Forms.Application.RunDialog
System.Windows.Forms.Form.ShowDialog
between the ShowDialog and the FormClosing.
CloseReason is "None"
Load runs to the end, as does VisibleChanged (though Activated never gets called).
There's no sign of any Exceptions being thrown.
Intellitrace doesn't show anything going on.
After the form closes, the DialogResult is "Cancel" (There's no reference to DialogResult in the form or its Designer)
I'm not doing any explicit threading
I'd appreciate any suggestions either as to what's going on or how to go about finding out.
Thanks.
In my case I was setting the DialogResult property on the load event to Cancel, and that was causing the dialog to close immediately after Load. I've set it to the default None and now I only set it to other value on the Click event of a button when I really need to close it.
Well, this will probably do nobody any good, but here's how I solved the problem:
There was a line in the Load method that read
Me.Text = ""
I have no idea what it was doing there (this isn't my code, thank goodness), especially since the value gets set again later on, but taking that line out stopped the form from mysteriously closing. Go figure.
I had a similar problem. In my case it was due to not specifying the parent window on the ShowDialog(). The dialog associated with the window that was topmost, which happened to be a combobox drop-down that was going away.
In my case, I changed the ShowDialog() call to use my application's main window as the parent, and problem solved.
Been debugging for couple of hours with the same problem. In my case the likely reason was that the parent form has setting ShowInTaskbar = false in Load event, while my form had this set to true in the designer. For some reason this caused the dialog result to be set to Cancel during initialization.

Need to force refresh on a WPF Label

I am making an asynchronous call to a web service. Since it might take a few seconds there is a status Label used to let the user know what's going on. But even though the call is async the first call seems to block for a few seconds and the status label takes too long to get updated. In WinForms I could force the label to refresh (using Update() I think) but not in WPF. Any super easy ways to get this working?
Thanks,
Gerry
You could move the entire call logic into a QueueWorkUserItem or BackgroundWorker block. That way the first proxy initialization would not block the UIThread (before the async. Begin/End pattern kicks in). Assuming that you are using databinding the object exposing the property bound to the Label implemented INotifyPropertyChanged everything should happen automagically.
I'd (wildly) guess that the blocking is due to the creation/initialization of the service proxy classes. If so, you could try to create the proxy earlier, or call your asynchronous web service in another thread.
The general answer to your question about refreshing controls... I have always relied on data binding to do this. That won't help though if the main UI thread is stuck doing something. And if the UI thread is stuck, I don't know that there's any way to get it to draw.
There isn't a way to tell the label to refresh that will actually work in your case. If the UI is being blocked, it won't refresh. Basically, when you actually get to the point where you update the label's text, it will show in WPF. The only possible exception that I can think to that would be if you are using a non-WPF control but even then it should work.
My suggestion would be to update the label before you perform the first action (even before variables are initialized, since this might be where the issue actually is). Here is a pseudocode example of what I mean (just in case I wasn't clear):
private void KickOffProcess()
{
label1.Text = "Processing ..."; //This is where you need to move the label update code
AsyncCall();
}

Close all open modal dialog windows

I have a WPF application that has several modal window used for various purposes. This is easily accomplished by using the ShowDialog function. However, in my application I have a timer to measure idle time (i.e. no mouse moves or key strokes) that will cause the user to be logged off. Is there a way (when this timer fires) to find and close all open modal windows without tracking each explicitly?
Update
I would also like to close any MessageBox.Show instances. Is this possible?
Thanks,
Matt
Have you tried to iterate the Application.Current.Windows collection, and close all these that are not the Application.Current.MainWindow?
Jogy
Is there a way (when this timer fires) to find and close all open modal windows without tracking each explicitly?
You could use ComponentDispatcher.IsThreadModal to check to see if you're UI thread is in a modal state. If it is, the Application.Current.Windows property will give you the list of opened Windows.
If you only have a single MainWindow, you could close any others (as they'd be your modal dialogs), but if you have multiple windows, you'd have to check each one.
Unfortunately, there's no direct API to determine whether a specific Window is modal - but there is a private variable in the Window class you could use to do this. For example, the following method uses reflection to determine whether a Window is modal:
public static bool IsModal(Window window)
{
Type type = typeof(Window);
var field = type.GetField("_showingAsDialog", BindingFlags.Instance | BindingFlags.NonPublic);
return field.GetValue(window);
}
This is, unfortunately, subject to change (since it's using undocumented private members).

WPF - Why isn't Keyboard.Focus() working?

have a TextBox item (MyTextBox) on a TabItem control. I have code that looks as follows:
MyTextBox.Focus();
Keyboard.Focus(MyTextBox);
When I run this code through the debugger I see the following after the lines are executed:
MyTextBox.IsFocused = true
MyTextBox.IsKeyboardFocused = false
Can anyone tell me why the textbox isn't receiving keyboard focus? It's just a standard TextBox control that is enabled.
When you try to set Focus to an element besides the things enumerated above by our coleague, you must also know that WPF does not allow cross threaded operations.
In some cases this exception is not raised like in the Focus method call case. What I've done to fix this issue is to call all the code that involves Keyboards focus in an action.
This action is ran inside the control dispatcher to make sure that my code is not being executed from another thread than the UI thread (e.g. timer event or an event raised from another thread):
[UIElement].Dispatcher.BeginInvoke(
new Action(
delegate{
/// put your Focus code here
}
)
);
MyTextBox.IsKeyboardFocused is false because you are looking at it under debugger and the keyboard focus is probably in your Visual Studio... Try debugging focus without breakpoints (e.g. Debug.Write or trace brakepoints) to see actual values of MyTextBox.IsKeyboardFocused in runtime.
Also notice that Focus() method returns boolean value that indicates whether focus was successfully set. Does it return False in your case? If yes, I would suggest stepping into Focus() method in order to find out what is wrong.
3 important properties must be true: IsVisible="True", Focusable="True". IsEnabled="True".
To be focusable, Focusable and IsEnabled must both be true.
http://msdn.microsoft.com/en-us/library/system.windows.uielement.focus.aspx
The accepted answer here does not solve the problem of textboxes who dont gain focus, no matter what the debugger tells you. If you have and can write to your textbox, then you have it keyboard-focused.
I found this here solving the problem (and actually gaining focus, not just settings the values so it looks like focus in the debugger), it comes very close to Pavlov's answer but with the "Focus code" : Keyboard.Focus does not work on text box in WPF
This worked for me (had to do UpdateLayout, otherwise Focus() didn't work immediately after changing tab from script)
tabControl.SelectedIndex = 2;
this.UpdateLayout();
txtMyTextBox.Focus();
It's important where your first two lines of code are executed.
If they are in an event handler that relates to the user pressing a key, using the mouse, altering the visibility of a control, or otherwise taking an action that might have an impact on focus, I find manually calling Focus() often doesn't work.
My theory is that internally, WPF operates as follows:
User or code takes action which could have an impact on focus, e.g. a TextBox control becomes enabled inside a focus scope which previously had no focusable control.
WPF notifies various event handlers, including yours which calls Focus().
WPF updates focus based on the state changes in step 1. This overrides whatever you did in step 2.
That is why this answer suggests to call your Focus() in a queued callback which will be executed after step 3.
Side note: you don't need to call both UIElement.Focus and Keyboard.Focus since the first includes the second (at least if you trust the Microsoft docs).
In conclusion, replace your first two lines of code with this:
// using System.Windows.Threading;
Dispatcher.BeginInvoke(DispatcherPriority.Input, MyTextBox.Focus);

Resources