Closing child window minimizes parent - wpf

The following code demonstrates an issue I'm having where closing a child window minimizes the parent window, which I dont want to happen.
class SomeDialog : Window
{
protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
{
base.OnMouseDoubleClick(e);
new CustomMessageBox().ShowDialog();
}
}
class CustomMessageBox : Window
{
public CustomMessageBox()
{
Owner = Application.Current.MainWindow;
}
}
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
{
base.OnMouseDoubleClick(e);
new SomeDialog() { Owner = this }.Show();
}
}
Window1 is the main application window.
SomeDialog is a window that pops up on some event within Window1(double clicking window1 in the example) that needs to be modeless.
CustomMessageBox is a window that pops up on some event within "SomeDialog" (double clicking SomeDialog in the example) that needs to be modal.
If you run the application, and then double click Window1's content to bring up SomeDialog, and then you then double click SomeDialog's content to bring up the CustomMessagebox.
Now you close CustomMessagebox. Fine.
Now if you close SomeDialog, Window1 minimizes? Why is it minimizing and how can I stop it?
Edit : It appears the workaround is rather simple, using the technique suggesrted by Viv.
class SomeDialog : Window
{
protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
{
base.OnMouseDoubleClick(e);
new CustomMessageBox().ShowDialog();
}
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
base.OnClosing(e);
Owner = null;
}
}

Why is it minimizing and how can I stop it?
Not sure about the "Why" maybe you can report it as a bug and see what they reply with as with a non-modal dialog you do not expect this to happen.
As for a workaround, Try something like this:
public partial class MainWindow : Window {
...
protected override void OnMouseDoubleClick(MouseButtonEventArgs e) {
base.OnMouseDoubleClick(e);
var x = new SomeDialog { Owner = this };
x.Closing += (sender, args) => {
var window = sender as Window;
if (window != null)
window.Owner = null;
};
x.Show();
}
}
^^ This should prevent the MainWindow(parent) from minimizing when SomeDialog is closed.

My workaround for this interesting problem is to activate the MainWindow once and after that activate the SomeDialog window again.
class SomeDialog : Window
{
protected override void OnMouseDoubleClick(MouseButtonEventArgs e)
{
base.OnMouseDoubleClick(e);
new CustomMessageBox().ShowDialog();
Owner.Activate();
Activate();
}
}

A very late answer... I just sat having this same issue and Viv's workaround solved it for me aswell. As for the "Why" part of the answer, i believe it happens when your child window spawns a child window of its own in its lifetime.
For my experience it occured whenever pressing my Save button, which is in a flow which requires a child window to be opened. But pressing the Cancel (or escape) or the windows default quit button did not invoke the issue.

First, as your code stands, I can confirm this strange behaviour. There are two things that I noticed here. The first is that the SomeDialog.Owner is not set, or that it ends up with a null value with this code:
new SomeDialog() { Owner = this }.Show();
Adding this code fixes that problem:
public SomeDialog()
{
Owner = Application.Current.MainWindow;
}
Unfortunately, this doesn't stop the MainWindow from being minimised when the child Window is closed. Then I found that I could stop it from being minimised, but only when calling new SomeDialog().ShowDialog(); instead of new SomeDialog().Show(); However, that makes this Window into a dialog, which is not what you're after I believe.

We had similar problem, but cause was quite simple. Method Close() of Window was called twice. After we had removed second call, all got back to normal.

Related

Winforms WebBrowser control without IE popups not appearing [duplicate]

I am trying to implement a simple web browser control in one of my apps. This is to help integrate a web app into a toolset i am creating.
The problem is, this web app absolutly loves popup windows....
When a popup is opened, it opens in an IE window which is not a child of the MDI Container form that my main window is part of.
How can i get any and all popups created by clicking links in my WebBrowser to be a child of my MDI container (similar to setting the MDIParent property of a form)?
Thanks in advance.
The web browser control supports the NewWindow event to get notified about a popup window. The Winforms wrapper however does not let you do much with it, you can only cancel the popup. The native COM wrapper permits passing back a new instance of the web browser, that instance will then be used to display the popup.
Taking advantage of this requires some work. For starters, use Project + Add Reference, Browse tab and select c:\windows\system32\shdocvw.dll. That adds a reference to the native COM interface.
Create a form that acts as the popup form. Drop a WebBrowser on it and make its code look similar to this:
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
}
public WebBrowser Browser {
get { return webBrowser1; }
}
}
The Browser property gives access to the browser that will be used to display the web page in the popup window.
Now back to the main form. Drop a WebBrowser on it and make its code look like this:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
webBrowser1.Url = new Uri("http://google.com");
}
SHDocVw.WebBrowser nativeBrowser;
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
nativeBrowser = (SHDocVw.WebBrowser)webBrowser1.ActiveXInstance;
nativeBrowser.NewWindow2 += nativeBrowser_NewWindow2;
}
protected override void OnFormClosing(FormClosingEventArgs e) {
nativeBrowser.NewWindow2 -= nativeBrowser_NewWindow2;
base.OnFormClosing(e);
}
void nativeBrowser_NewWindow2(ref object ppDisp, ref bool Cancel) {
var popup = new Form2();
popup.Show(this);
ppDisp = popup.Browser.ActiveXInstance;
}
}
The OnLoad method obtains a reference to the native COM interface, then subscribes an event handler to the NewWindow2 event. I made sure to unsubscribe that event in the FormClosing event handler, not 100% sure if that's necessary. Better safe then sorry.
The NewWindow2 event handler is the crux, note that the first argument allows passing back an untyped reference. That should be the native browser in the popup window. So I create an instance of Form2 and Show() it. Note the argument to Show(), that ensures that the popup is an owned window. Substitute this as necessary for your app, I assume you'd want to create an MDI child window in your case.
Do beware that this event doesn't fire for the window displayed when Javascript uses alert(). The browser doesn't treat that window as an HTML popup and doesn't use a browser window to display it so you cannot intercept or replace it.
I found that the best way to do this was to implement/sink the NewWindow3 event
Add the reference to c:\windows\system32\shdocvw.dll as mentioned in the other answers here.
Add event handler
SHDocVw.WebBrowser wbCOMmain = (SHDocVw.WebBrowser)webbrowser.ActiveXInstance;
wbCOMmain.NewWindow3 += wbCOMmain_NewWindow3;
Event method
void wbCOMmain_NewWindow3(ref object ppDisp,
ref bool Cancel,
uint dwFlags,
string bstrUrlContext,
string bstrUrl)
{
// bstrUrl is the url being navigated to
Cancel = true; // stop the navigation
// Do whatever else you want to do with that URL
// open in the same browser or new browser, etc.
}
Set "Embed Interop Types" for the "Interop.SHDocVw" assembly to false
Set the "local copy" to true.
Source for that help MSDN Post
Refining Hans answer, you can derive the WebBrowser for accessing the COM without adding the reference. It is by using the unpublished Winforms WebBrowser.AttachInterface and DetachInterface methods.
More elaborated here.
Here is the code:
Usage (change your WebBrowser instance to WebBrowserNewWindow2)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.webBrowser1.NewWindow2 += webBrowser_NewWindow2;
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
webBrowser1.NewWindow2 -= webBrowser_NewWindow2;
base.OnFormClosing(e);
}
void webBrowser_NewWindow2(object sender, WebBrowserNewWindow2EventArgs e)
{
var popup = new Form1();
popup.Show(this);
e.PpDisp = popup.Browser.ActiveXInstance;
}
public WebBrowserNewWindow2 Browser
{
get { return webBrowser1; }
}
}
Code:
using System;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace SHDocVw
{
public delegate void WebBrowserNewWindow2EventHandler(object sender, WebBrowserNewWindow2EventArgs e);
public class WebBrowserNewWindow2EventArgs : EventArgs
{
public WebBrowserNewWindow2EventArgs(object ppDisp, bool cancel)
{
PpDisp = ppDisp;
Cancel = cancel;
}
public object PpDisp { get; set; }
public bool Cancel { get; set; }
}
public class WebBrowserNewWindow2 : WebBrowser
{
private AxHost.ConnectionPointCookie _cookie;
private WebBrowser2EventHelper _helper;
[PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")]
protected override void CreateSink()
{
base.CreateSink();
_helper = new WebBrowser2EventHelper(this);
_cookie = new AxHost.ConnectionPointCookie(
this.ActiveXInstance, _helper, typeof(DWebBrowserEvents2));
}
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
protected override void DetachSink()
{
if (_cookie != null)
{
_cookie.Disconnect();
_cookie = null;
}
base.DetachSink();
}
public event WebBrowserNewWindow2EventHandler NewWindow2;
private class WebBrowser2EventHelper : StandardOleMarshalObject, DWebBrowserEvents2
{
private readonly WebBrowserNewWindow2 _parent;
public WebBrowser2EventHelper(WebBrowserNewWindow2 parent)
{
_parent = parent;
}
public void NewWindow2(ref object pDisp, ref bool cancel)
{
WebBrowserNewWindow2EventArgs arg = new WebBrowserNewWindow2EventArgs(pDisp, cancel);
_parent.NewWindow2(this, arg);
if (pDisp != arg.PpDisp)
pDisp = arg.PpDisp;
if (cancel != arg.Cancel)
cancel = arg.Cancel;
}
}
[ComImport, Guid("34A715A0-6587-11D0-924A-0020AFC7AC4D"),
InterfaceType(ComInterfaceType.InterfaceIsIDispatch),
TypeLibType(TypeLibTypeFlags.FHidden)]
public interface DWebBrowserEvents2
{
[DispId(0xfb)]
void NewWindow2(
[In, Out, MarshalAs(UnmanagedType.IDispatch)] ref object ppDisp,
[In, Out] ref bool cancel);
}
}
}
I know the question is very old but I solved it this way: add new reference, in COM choose Microsoft Internet Controls and in the code, before the click that opens a new window add the following:
SHDocVw.WebBrowser_V1 axBrowser = (SHDocVw.WebBrowser_V1)webBrowser1.ActiveXInstance;
axBrowser.NewWindow += axBrowser_NewWindow;
and then add the following method:
void axBrowser_NewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed)
{
Processed = true;
webBrowser1.Navigate(URL);
}

How to auto-close the Caliburn Dialog window?

I have a ViewModel defined like
public class PlayerViewModel : Screen, IDiscoverableViewModel
I am showing a dialog pop up as
var result = await _dialogManager.ShowDialogAsync(item, new List<DialogResult>() { DialogResult.Cancel });
Here item is the another ViewModel which shows UI from the related View. This pop up is showing some information and needs to be auto closed after few seconds in case user doesn't select Cancel button.
Following is the Timer tick event that is getting fired after 10 seconds.
void timer_Tick(object sender, EventArgs e)
{
this.DialogHost().TryClose(DialogResult.Cancel);
}
But it's not working and throwing exception as this.DialoHost() is getting null always. I tried this solution but it is closing the whole ViewModel instead I want to close only the dialog window.
Could you confirm if your 'pop-up viewmodel' is deriving from Screen ? If so, TryClose should work. Could you please verify it ? Sample code for closing.
public class CreatePersonViewModel:Screen
{
System.Timers.Timer _timer = new Timer(5000);
public CreatePersonViewModel()
{
_timer.Elapsed += (sender, args) =>
{
_timer.Enabled = false;
TryClose(true);
};
_timer.Start();
}
}

Is there a way to keep additional windows active when showing a modal window?

I'm afraid the answer is probably no...but some background. To draw a custom border on a window where the sizing logic works beyond the visible border (as it does on windows 10) I added layered windows around the edges to capture the messages and then forward them to the central window. This worked great until the form was shown modaly, at which point all the edge windows were automatically disabled. Obviously this is by design...but I'm not sure if there is some way around it. I tried making the edge windows owned by the central window, but that didn't work.
Or maybe there is a better approach entirely.
Here's a sample of the issue:
public partial class Form1 : Form
{
public Form1()
{
}
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
Form f2 = new Form();
f2.Text = "Non Modal";
f2.Show();
Form f3 = new Form();
f3.Text = "Modal";
f3.ShowDialog(this);
}
}
I think you can fake the modal window, so that it is not modal but disable the caller. I used this in a own project. I did it this way:
//Setup small Interface
public interface IDialog
{
//Our own Event which tell the caller if the Dialog is active/inactive
public event DialogChangedEventArgs DialogChanged;
}
//Setup EventArgs for our own Event
public class DialogChangedEventArgs : EventArgs
{
public bool DialogActive{get;}
public DialogChangedEventArgs(bool dialogActive)
{
DialogActive = dialogActive;
}
}
//Setup the Form which act as Dialog in any other form
public class Form2 : Form, IDialog
{
public event EventHandler<DialogChangedEventArgs> DialogChanged;
//If this Form is shown we fire the Event and tell subscriber we are active
private void Form2_Shown(object sender, EventArgs e)
{
DialogChanged?.Invoke(this, true);
}
//If the user close the Form we telling subscriber we go inactive
private void Form2_Closing(object sender, CancelEventArgs e)
{
DialogChanged?.Invoke(this, false);
}
}
public class Form1 : Form
{
//Setup our Form2 and show it (not modal here!!!)
private void Initialize()
{
Form2 newForm = new Form2();
newForm.DialogChanged += DialogChanged;
newForm.Show();
}
private void Form2_DialogChanged(object sender, DialogChangedEventArgs e)
{
//Now check if Form2 is active or inactive and enable/disable Form1
//So just Form1 will be disabled.
Enable = !e.DialogActive;
}
}
It's really simple. Just use an event to tell your first Form: Hey iam second Form and active. Then you can disable the first Form with while second is active. You have the full control which forms are active or not. Hope this helps.

Open other window from window

I have some academic question here. I read this question WPF MVVM Get Parent from VIEW MODEL and concluded that ViewModel should not opens any windows itself. So I use Messenger now to send message to ViewModel's Window and Window opens other window - NewWindow. It works fine, but what if NewWindow does something and get some Result has to be passed in MainWindow for further actions? More detailed:
NewWindow opened by button click in Window (OpenNewWindowCommand) and made some calculations.
After calculations NewWindow got some Result (does't matter what exactly is it) and rise a corresponding event - GotSomeResult, where event arg is Result.
This Result has to be passed in MainWindow to further processing, so I bind event handler to GotSomeResult event.
Below you can see all required code to illustrate this scenario.
MainWindow code-behind:
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
Messenger.Default.Register<NewWindowMessage>(this, OpenNewWindow);
}
private void OpenNewWindow(NewWindowMessage message)
{
var newWindow = new NewWindow();
var newWindowViewModel = (NewWindowViewModel) message.Target;
newWindowViewModel.GotSomeResult += ((MetaWindowViewModel)DataContext).ProcessResult;
newWindow.Owner = this;
newWindow.DataContext = newWindowViewModel;
newWindow.ShowDialog();
}
MainWindow ViewModel:
public void OpenNewWindowCommand()
{
Messenger.Default.Send(new NewWindowMessage(this, new NewWindowViewModel("OpenWindow"), String.Empty));
}
public void ProcessResult(Object someResult)
{
// Any actions with result
}
newWindowViewModel.GotSomeResult += ((MetaWindowViewModel)DataContext).ProcessResult; --- this string seems problem for me. Is it correct to get access to public method of ViewModel right in theView? Does it violent MVVM pattern?
Why don't you hook the handler to GotSomeResult at the VM level, ie :
public void OpenNewWindowCommand()
{
var newWindowViewModel = new NewWindowMessage(this, new NewWindowViewModel("OpenWindow"), String.Empty)
newWindowViewModel.GotSomeResult += this.ProcessResult;
Messenger.Default.Send();
}
It removes the references to your ViewModel in your codebehind (which indeed should be avoided):
private void OpenNewWindow(NewWindowMessage message)
{
var newWindow = new NewWindow();
newWindow.Owner = this;
newWindow.DataContext = message.Target;
newWindow.ShowDialog();
}

Custom MessageBox using Window

In regard to the code below.
If I use the built in MessageBox, then the previous MessageBox has to be closed before the next one is displayed.
How can I achieve this with a Window so that I can create a custom message box? I tried using the ShowDialog method, but whilst this does create Modal windows, it still shows them all at the same time cascaded.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 3; ++i)
{
Dispatcher.BeginInvoke(new Action(() => ShowDialog2()));
}
}
void ShowDialog2()
{
//MessageBox.Show("A message");
Window w = new Window() { Width = 200, Height = 200, Content = "SomeText" };
w.ShowDialog();
}
}
Open first instance of window with ShowDialog and consequent instances of window with Show method.
Show open a non-modal window whereas ShowDialog open modal window.

Resources