In my WPF application I would like to subscribe to some event/callbeck/whatever that tells me whenever a dialog window opens (and closes) in my application.
I found the window collection but this is a simple container and it doesn't seem to provide any means of subscription.
I also tried using event handlers but there seems not be an event that tells me what I need.
Any ideas?
One way to do it without a base class is adding a handler to MainWindow deactivated
If a new window is opened, the main window will lose focus = your "new window event"
private readonly List<Window> openWindows = new List<Window>();
public void ApplicationMainWindow_Deactivated(object sender, EventArgs e)
{
foreach (Window window in Application.Current.Windows)
{
if (!openWindows.Contains(window) && window != sender)
{
// Your window code here
window.Closing += PopupWindow_Closing;
openWindows.Add(window);
}
}
}
private void PopupWindow_Closing(object sender, CancelEventArgs e)
{
var window = (Window)sender;
window.Closing -= PopupWindow_Closing;
openWindows.Remove(window);
}
Without creating a Base class for all your windows where you can hook into the opened event (or manually adding the opened event to each window), I'm not sure how you'd be able to know when new windows were create.
There may be a more elegant way, but you could poll the Application.Current.Windows to see if any new windows were created while keeping track of the one's you've found.
Here is a crude example that will demonstrate how to use a DispatchTimer to poll for new windows, keep track of found windows and hook into the closed event.
Code Behind
public partial class MainWindow : Window
{
private DispatcherTimer Timer { get; set; }
public ObservableCollection<Window> Windows { get; private set; }
public MainWindow()
{
InitializeComponent();
// add current Window so we don't add a hook into it
Windows = new ObservableCollection<Window> { this };
Timer = new DispatcherTimer( DispatcherPriority.Background );
Timer.Interval = TimeSpan.FromMilliseconds( 500 );
Timer.Tick += ( _, __ ) => FindNewWindows();
Timer.Start();
this.WindowListBox.ItemsSource = Windows;
this.WindowListBox.DisplayMemberPath = "Title";
}
private void FindNewWindows()
{
foreach( Window window in Application.Current.Windows )
{
if( !Windows.Contains( window ) )
{
window.Closed += OnWatchedWindowClosed;
// inserting at 0 so you can see it in the ListBox
Windows.Insert( 0, window );
Feedback.Text = string.Format( "New Window Found: {0}\r\n{1}",
window.Title, Feedback.Text );
}
}
}
private void OnWatchedWindowClosed( object sender, EventArgs e )
{
var window = (Window)sender;
Windows.Remove( window );
Feedback.Text = string.Format( "Window Closed: {0}\r\n{1}",
window.Title, Feedback.Text );
}
private void CreateWindowButtonClick( object sender, RoutedEventArgs e )
{
string title = string.Format( "New Window {0}", DateTime.Now );
var win = new Window
{
Title = title,
Width = 250,
Height = 250,
Content = title,
};
win.Show();
e.Handled = true;
}
}
XAML
<Grid>
<ListBox Name="WindowListBox"
Width="251"
Height="130"
Margin="12,12,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top" />
<TextBox Name="Feedback"
Width="479"
Height="134"
Margin="12,148,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
VerticalScrollBarVisibility="Auto" />
<Button Name="CreateWindowButton"
Width="222"
Height="130"
Margin="269,12,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Click="CreateWindowButtonClick"
Content="Create New Window"
FontSize="20" />
</Grid>
Click away and create as many new windows as you want; then close them. You'll see the feedback as it happens. Granted, there will be a 500ms delay whenever a new window is created since the DispatchTimer's interval is set at 500ms.
You could register a class handler in App.cs as demonstrated here
https://gist.github.com/mwisnicki/3104963
...
EventManager.RegisterClassHandler(typeof(UIElement), FrameworkElement.LoadedEvent, new RoutedEventHandler(OnLoaded), true);
EventManager.RegisterClassHandler(typeof(UIElement), FrameworkElement.UnloadedEvent, new RoutedEventHandler(OnUnloaded), true);
...
private static void OnLoaded(object sender, RoutedEventArgs e)
{
if (sender is Window)
Console.WriteLine("Loaded Window: {0}", sender);
}
private static void OnUnloaded(object sender, RoutedEventArgs e)
{
if (sender is Window)
Console.WriteLine("Unloaded Window: {0}", sender);
}
The link above seems to register an empty handler on instances to make things work properly.
I have never heard of any global open/close event.
It should somehow be possible to do, but that provides that you have control over all windows opening and closing. Like if you build a "base window" (which naturally inherit "Window") that all your dialogs windows inherit from.
Then you clould have a static event on the "base window" which you fire from the base window's opening and closing/closed (or unloaded) events, sending "this" as "sender".
You can attafh to that static event in your App.xaml.cs class.
It's a hack, but it's possible.
Related
Im new in WPF and Im creating a custom dialog (or a message box) in WPF.
My problem is I cant change everything behind my custom dialog to Opacity=0.5. Only the form who called the custom dialog..
I just want to show my dialog box like in Windows 8.1
Anything would be highly appreciated.
TIA!
Set a property in your MainWindow that controls Opacity of the LayoutRoot. This will change the opacity of your App when the dialog is displayed.
Sample code:
<Grid Name="LayoutRoot" Opacity="{Binding MainWindowOpacity}">
<StackPanel>
<Button Click="Button_Click" Content="Click Me to Show Dialog"/>
<TextBlock Text="WPF" FontSize="72" Margin="50" Foreground="Orange" HorizontalAlignment="Center"/>
</StackPanel>
</Grid>
and
public partial class MainWindow : Window
{
public double MainWindowOpacity
{
get { return (double)GetValue(MainWindowOpacityProperty); }
set { SetValue(MainWindowOpacityProperty, value); }
}
// Using a DependencyProperty as the backing store for MainWindowOpacity. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MainWindowOpacityProperty =
DependencyProperty.Register("MainWindowOpacity", typeof(double), typeof(MainWindow), new PropertyMetadata(1.0));
public MainWindow()
{
InitializeComponent();
DataContext = this;
Loaded += MainWindow_Loaded;
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//if (MainWindowOpacity < 1) MainWindowOpacity = 1.0;
//else MainWindowOpacity = 0.5;
MainWindowOpacity = 0.5;
// show dialog
// boilerplate code from http://stackoverflow.com/questions/6417558/modal-dialog-not-showing-on-top-of-other-windows
Window window = new Window()
{
Title = "WPF Modal Dialog",
ShowInTaskbar = false, // don't show the dialog on the taskbar
Topmost = true, // ensure we're Always On Top
ResizeMode = ResizeMode.NoResize, // remove excess caption bar buttons
Owner = Application.Current.MainWindow,
Width = 300,
Height = 200
};
window.ShowDialog();
MainWindowOpacity = 1.0;
}
}
and the result:
You could add a static method to App.xaml like this:
public partial class App : Application
{
public static void SetWindowsToOpacity(double dOpacity, Window ignoreWindow)
{
foreach (Window win in System.Windows.Application.Current.Windows)
{
if (win != ignoreWindow)
{
win.Opacity = dOpacity;
}
}
}
}
Pass in the Dialog window that you do not want to be set to lower opacity and an opacity value for all the rest.
Call the method like this:
private void button_Click(object sender, RoutedEventArgs e)
{
Window1 dialog = new Window1();
App.SetWindowsToOpacity(0.5, dialog);
dialog.ShowDialog();
App.SetWindowsToOpacity(1.0, null);
}
I'm using the MahApps Metro window style, and I want to capture the event when the user clicks on the close button of the window.
I've set my ShutdownMode to OnExplicitShutdown so I need to call Application.Current.Shutdown(); when that button is clicked
How can I do this ?
I believe that I am also trying to do the same thing as you (bind to the close window button) using WPF and MahApps.Metro. I wasn't able to find a way yet to bind to that command explicitly, but I was able to accomplish this by setting the ShowCloseButton property to false (to hide it) and then created my own close window command button and handled the logic in my viewmodel. Took me some digging, but I found that you can easily add your own window command controls in the command bar with MahApps.Metro just add similar markup to your XAML:
<Controls:MetroWindow.WindowCommands>
<Controls:WindowCommands>
<Button Content="X" Command="{Binding CancelCommand}" />
</Controls:WindowCommands>
</Controls:MetroWindow.WindowCommands>
You need to create a DependencyProperty to handle the close window behavior:
DependencyProperty
namespace MyApp.DependencyProperties
{
public class WindowProperties
{
public static readonly DependencyProperty WindowClosingProperty =
DependencyProperty.RegisterAttached("WindowClosing", typeof(RelayCommand), typeof(WindowProperties), new UIPropertyMetadata(null, WindowClosing));
public static object GetWindowClosing(DependencyObject depObj)
{
return (RelayCommand)depObj.GetValue(WindowClosingProperty);
}
public static void SetWindowClosing(DependencyObject depObj, RelayCommand value)
{
depObj.SetValue(WindowClosingProperty, value);
}
private static void WindowClosing(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
var element = (Window)depObj;
if (element != null)
element.Closing += OnWindowClosing;
}
private static void OnWindowClosing(object sender, CancelEventArgs e)
{
RelayCommand command = (RelayCommand)GetWindowClosing((DependencyObject)sender);
command.Execute((Window)sender);
}
}
}
In your ViewModel
public RelayCommand WindowClosedCommand { get; set; }
private void WindowClose()
{
Application.Current.Shutdown();
}
In Constructor of ViewModel
this.WindowCloseCommand = new RelayCommand(WindowClose);
In your XAML
<mah:MetroWindow x:Class="MyApp.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mah="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
xmlns:dp="clr-namespace:MyApp.DependencyProperties"
dp:WindowProperties.WindowClosing="{Binding WindowClosedCommand}" />
Since the solution from gotapps.net did't worked for me because I did't found how to programatically do that (My window does not have the Xaml file, it's just a base class). I found another workaround to use the same button to close the Window as follows:
internal class BaseWindow : MetroWindow
{
public BaseWindow()
{
this.Loaded += BaseWindow_Loaded;
}
void BaseWindow_Loaded(object sender, EventArgs e)
{
Button close = this.FindChild<Button>("PART_Close");
close.Click += close_Click;
}
void close_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown(0);
}
}
You can use "Closing" or "Closed" event
Closing handler gets triggered when user clicks on the Close button. This also gives you control on whether the application should be closed.
Similarly, Closed handler gets triggered just before the window is closed
<Controls:MetroWindow x:Class="MyClass.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
Title="My Class"
Closing="MainWindow_OnClosing">
</Controls:MetroWindow>
I have a WPF application which need support screen reader(especially JAWS). The issue is, JAWS does not announce anything, when the list view items have changed(added, removed). And blind users totally do not know what has happened. I there any way to force the screen reader announce some text, when trying to add/remove item from list view control? and How can I do that?
If the JAWS reader does not support this function, you can implement it yourself by SpeechSynthesizer. Example the voice playback:
using System.Speech.Synthesis;
SpeechSynthesizer MySpeechSynthesizer = new SpeechSynthesizer();
MySpeechSynthesizer.Speak("Hello!");
I used the example of a ObservableCollection that is assigned ListBox. ObservableCollection is an event CollectionChanged, in that contains the enumeration of acts performed on the collection [MSDN]:
Member name Description
------------ ------------
Add One or more items were added to the collection.
Move One or more items were moved within the collection.
Remove One or more items were removed from the collection.
Replace One or more items were replaced in the collection.
Reset The content of the collection changed dramatically.
This event will be implemented like this:
// Set the ItemsSource
SampleListBox.ItemsSource = SomeListBoxCollection;
// Set handler on the collection
SomeListBoxCollection.CollectionChanged += new NotifyCollectionChangedEventHandler(SomeListBoxCollection_CollectionChanged);
private void SomeListBoxCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
// Some actions, in our case - speech
}
}
Below is my example:
XAML
<Window x:Class="JAWShelp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
WindowStartupLocation="CenterScreen">
<Grid>
<ListBox Name="MyListBox" DisplayMemberPath="Name" SelectedIndex="0" Width="100" Height="100" Loaded="MyListBox_Loaded" />
<WrapPanel Width="200" Height="30" Margin="40,150,0,0">
<Button Name="AddButton" Padding="5" Content="Add item" VerticalAlignment="Bottom" Click="AddButton_Click" />
<Button Name="RemoveButton" Padding="5" Margin="30,0,0,0" Content="Remove item" VerticalAlignment="Bottom" Click="RemoveButton_Click" />
</WrapPanel>
</Grid>
</Window>
Code behind
// using System.Speech.Synthesis;
// using System.Collections.ObjectModel;
// using System.Collections.Specialized;
public partial class MainWindow : Window
{
public class Person
{
public string Name
{
get;
set;
}
}
private ObservableCollection<Person> DataForListBox = new ObservableCollection<Person>();
public MainWindow()
{
InitializeComponent();
}
private void MyListBox_Loaded(object sender, RoutedEventArgs e)
{
DataForListBox.Add(new Person()
{
Name = "Peter Orange",
});
MyListBox.ItemsSource = DataForListBox;
DataForListBox.CollectionChanged += new NotifyCollectionChangedEventHandler(DataForListBox_CollectionChanged);
}
private void DataForListBox_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
SpeechSynthesizer MySpeechSynthesizer = new SpeechSynthesizer();
MySpeechSynthesizer.Speak("You are add item.");
}
if (e.Action == NotifyCollectionChangedAction.Remove)
{
SpeechSynthesizer MySpeechSynthesizer = new SpeechSynthesizer();
MySpeechSynthesizer.Speak("You are remove item.");
}
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
DataForListBox.Add(new Person()
{
Name = "Jack Rider",
});
}
private void RemoveButton_Click(object sender, RoutedEventArgs e)
{
DataForListBox.RemoveAt(1);
}
}
Without problems, you can add the reproduction text of Add/Remove item. You can also add play .wav file using PromptBuilder:
PromptBuilder MyPromptBuilder = new PromptBuilder();
MyPromptBuilder.AppendAudio("SomeFile.wav");
JAWS will only respond to controls that gain focus. I needed similar functionality in my application and resolved it with the following.
Add two hidden textbox controls to your layout.
<!--Controls used to announce accessibility messages for screen readers.-->
<TextBox x:Name="ATMessage_Silent" Height="1" Width="1" IsTabStop="False" AutomationProperties.Name=" "/>
<TextBox x:Name="ATMessage_Audible" Height="1" Width="1" IsTabStop="False"/>
Add a class to announce the messages. I found that to make it reliable I needed to pause briefly between passing focus between multiple controls. Otherwise JAWS doesn't reliably announce the messages.
public class AccessibilityMessage
{
private AccessibilityMessage(object sender, string message, double delay)
{
DispatcherTimer sleep = new DispatcherTimer();
int counter = 3;
try
{
if (accessibilityMessageAudibleControl != null && accessibilityMessageSilentControl != null)
{
sleep.Interval = TimeSpan.FromMilliseconds(delay);
// Update the message.
accessibilityMessageAudibleControl.SetValue(AutomationProperties.NameProperty, message);
// Give focus to the silent control.
accessibilityMessageSilentControl.IsTabStop = true;
accessibilityMessageSilentControl.Focus();
// Give focus to the message.
accessibilityMessageAudibleControl.IsTabStop = true;
accessibilityMessageAudibleControl.Focus();
// Use a timer to simulate a sleep. We need to pause briefly to give enough time
// for the screen reader to process the focus on the message control. After a brief
// pause we will give focus back to the original control. If we do not pause like
// this the screen reader will not reliably react to the message.
sleep.Tick += (s, e) =>
{
counter--;
// Check to see if it is time to focus the original control.
if (counter == 0)
{
// Return focus to the original control that triggered the message.
if (sender != null && sender is Control)
{
// Give focus back to the original control.
((Control)sender).Focus();
}
// Exit the timer.
sleep.Stop();
// Inform any listeners the message has been announced.
if (Announced != null)
Announced(this, null);
}
};
// Start the time.
sleep.Start();
}
else
{
throw new Exception("Accessibility message controls are not defined in the Application Manager. Unable to announce accessibility message.");
}
}
catch (Exception ex)
{
ErrorDialog.Show(ex, sender);
}
}
public event EventHandler Announced;
public static AccessibilityMessage Announce(object sender, string message, double delay = 250)
{
return new AccessibilityMessage(sender, message, delay);
}
}
Announce your messages. You can either simply make an announcement or using the Announced event you can make the announcement and then perform additional work after the announcement is made.
Make an announcement to inform the user to please wait while a data grid is loaded with data.
// Pass myGrid as the sender so it will receive focus after the announcement.
ApplicationManager.AccessibilityMessage.Announce(myGrid, "Loading purchase orders table, please wait.").Announced += (s, arg) =>
{
// MAKE WEB SERVICE CALL TO RETRIEVE DATA.
DataService svc = new DataService();
svc.ListPurchasOrdersCompleted += OnListPurchaseOrders_Completed();
svc.ListPurchaseOrders();
};
Make the announcement that the data has been loaded into the data grid.
private void OnListPurchaseOrders_Completed(object sender, AsyncCompletedEventArgs e)
{
try
{
if (e.Error == null)
{
myGrid.ItemsSource = e.Result();
// Pass myGrid as the sender so it will receive focus after the announcement.
AccessibilityMessage.Announce(myGrid, string.Format("Loaded {0} orders into the purchase orders table.", myGrid.Items.Count));
}
else
{
throw e.Error;
}
}
catch (Exception ex)
{
ErrorDialog.Show(ex, this);
}
}
Using this you can make announcements whenever you want simply by using the Announce() call. I originally implemented this for Silverlight. It should work for WPF as well.
The way I like to do it is have a height 0 TextBlock in the UI:
<TextBlock
x:Name="screenReaderText"
Height="0"
AutomationProperties.LiveSetting="Assertive" />
I then use this method to have it read something:
public void ReadTextToScreenReader(string text)
{
var peer = UIElementAutomationPeer.FromElement(this.screenReaderText);
if (peer != null)
{
this.screenReaderText.Text = text;
peer.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged);
}
}
Basically it's saying "Look, this control changed content, better read it out."
My application has several independent "top-level" windows, which all have completely different functions/workflows.
I am currently using ShowDialog() to make a WPF Window modal. The modal window is a child of one of the main windows. However, it is blocking all the top-level windows once it is open. I would like the dialog to block ONLY the parent window it was launched from. Is this possible?
I'm not sure if it matters, but the window that opens the dialog is the initial window of the app--so all other top-level windows are opened from it.
I had the same problem and implemented the modal dialog behavior as described in this post:
http://social.msdn.microsoft.com/Forums/vstudio/en-US/820bf10f-3eaf-43a8-b5ef-b83b2394342c/windowsshowmodal-to-parentowner-window-only-not-entire-application?forum=wpf
I also tried a multiple UI thread approach, but this caused problems with third-party libraries (caliburn micro & telerik wpf controls), since they are not built to be used in multiple UI threads. It is possible to make them work with multiple UI threads, but I prefer a simpler solution...
If you implement the dialog as described, you can not use the DialogResult property anymore, since it would cause a "DialogResult can be set only after Window is created and shown as dialog" exception. Just implement your own property and use it instead.
You need the following windows API reference:
/// <summary>
/// Enables or disables mouse and keyboard input to the specified window or control.
/// When input is disabled, the window does not receive input such as mouse clicks and key presses.
/// When input is enabled, the window receives all input.
/// </summary>
/// <param name="hWnd"></param>
/// <param name="bEnable"></param>
/// <returns></returns>
[DllImport("user32.dll")]
private static extern bool EnableWindow(IntPtr hWnd, bool bEnable);
Then use this:
// get parent window handle
IntPtr parentHandle = (new WindowInteropHelper(window.Owner)).Handle;
// disable parent window
EnableWindow(parentHandle, false);
// when the dialog is closing we want to re-enable the parent
window.Closing += SpecialDialogWindow_Closing;
// wait for the dialog window to be closed
new ShowAndWaitHelper(window).ShowAndWait();
window.Owner.Activate();
This is the event handler which re-enables the parent window, when the dialog is closed:
private void SpecialDialogWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
var win = (Window)sender;
win.Closing -= SpecialDialogWindow_Closing;
IntPtr winHandle = (new WindowInteropHelper(win)).Handle;
EnableWindow(winHandle, false);
if (win.Owner != null)
{
IntPtr parentHandle = (new WindowInteropHelper(win.Owner)).Handle;
// reenable parent window
EnableWindow(parentHandle, true);
}
}
And this is the ShowAndWaitHelper needed to achieve the modal dialog behavior (this blocks the execution of the thread, but still executes the message loop.
private sealed class ShowAndWaitHelper
{
private readonly Window _window;
private DispatcherFrame _dispatcherFrame;
internal ShowAndWaitHelper(Window window)
{
if (window == null)
{
throw new ArgumentNullException("window");
}
_window = window;
}
internal void ShowAndWait()
{
if (_dispatcherFrame != null)
{
throw new InvalidOperationException("Cannot call ShowAndWait while waiting for a previous call to ShowAndWait to return.");
}
_window.Closed += OnWindowClosed;
_window.Show();
_dispatcherFrame = new DispatcherFrame();
Dispatcher.PushFrame(_dispatcherFrame);
}
private void OnWindowClosed(object source, EventArgs eventArgs)
{
if (_dispatcherFrame == null)
{
return;
}
_window.Closed -= OnWindowClosed;
_dispatcherFrame.Continue = false;
_dispatcherFrame = null;
}
}
One option is to start the windows that you don't want affected by the dialog on a different thread. This may result in other issues for your application, but if those windows do really encapsulate different workflows, that may not be an issue. Here is some sample code I wrote to verify that this works:
<Window x:Class="ModalSample.MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="{Binding Identifier}" Height="150" Width="150">
<StackPanel>
<TextBox Text="{Binding Identifier}" />
<Button Content="Open Normal Child" Click="OpenNormal_Click" />
<Button Content="Open Independent Child" Click="OpenIndependent_Click" />
<Button Content="Open Modal Child" Click="OpenModal_Click" />
</StackPanel>
</Window>
using System.ComponentModel;
using System.Threading;
using System.Windows;
namespace ModalSample
{
/// <summary>
/// Interaction logic for MyWindow.xaml
/// </summary>
public partial class MyWindow : INotifyPropertyChanged
{
public MyWindow()
{
InitializeComponent();
DataContext = this;
}
private int child = 1;
private string mIdentifier = "Root";
public string Identifier
{
get { return mIdentifier; }
set
{
if (mIdentifier == value) return;
mIdentifier = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Identifier"));
}
}
private void OpenNormal_Click(object sender, RoutedEventArgs e)
{
var window = new MyWindow {Identifier = Identifier + "-N" + child++};
window.Show();
}
private void OpenIndependent_Click(object sender, RoutedEventArgs e)
{
var thread = new Thread(() =>
{
var window = new MyWindow {Identifier = Identifier + "-I" + child++};
window.Show();
window.Closed += (sender2, e2) => window.Dispatcher.InvokeShutdown();
System.Windows.Threading.Dispatcher.Run();
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
private void OpenModal_Click(object sender, RoutedEventArgs e)
{
var window = new MyWindow { Identifier = Identifier + "-M" + child++ };
window.ShowDialog();
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
I sourced this blog post for running a WPF window on a different thread.
How one can show dialog window (e.g. login / options etc.) before the main window?
Here is what I tried (it apparently has once worked, but not anymore):
XAML:
<Application ...
Startup="Application_Startup">
Application:
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
Window1 myMainWindow = new Window1();
DialogWindow myDialogWindow = new DialogWindow();
myDialogWindow.ShowDialog();
}
}
Outcome: myDialogWindow is shown first. When it is closed, the Window1 is shown as expected. But as I close Window1 the application does not close at all.
Here's the full solution that worked for me:
In App.xaml, I remove the StartupUri stuff, and add a Startup handler:
<Application x:Class="MyNamespace.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="ApplicationStart">
</Application>
In App.xaml.cs, I define the handler as follows:
public partial class App
{
private void ApplicationStart(object sender, StartupEventArgs e)
{
//Disable shutdown when the dialog closes
Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
var dialog = new DialogWindow();
if (dialog.ShowDialog() == true)
{
var mainWindow = new MainWindow(dialog.Data);
//Re-enable normal shutdown mode.
Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
Current.MainWindow = mainWindow;
mainWindow.Show();
}
else
{
MessageBox.Show("Unable to load data.", "Error", MessageBoxButton.OK);
Current.Shutdown(-1);
}
}
}
Okay apologizes, here is the solution:
My original question worked almost, only one thing to add, remove the StartupUri from the Application XAML and after that add the Show to main window.
That is:
<Application x:Class="DialogBeforeMainWindow.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="Application_Startup">
Above, StartupUri removed.
Add myMainWindow.Show() too:
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
Window1 myMainWindow = new Window1();
DialogWindow myDialogWindow = new DialogWindow();
myDialogWindow.ShowDialog();
myMainWindow.Show();
}
}
WPF sets App.Current.MainWindow to the first window opened. If you have control over the secondary window constructor, just set App.Current.MainWindow = Null there. Once your main window is constructed, it will be assigned to the App.Current.MainWindow property as expected without any intervention.
public partial class TraceWindow : Window
{
public TraceWindow()
{
InitializeComponent();
if (App.Current.MainWindow == this)
{
App.Current.MainWindow = null;
}
}
}
If you don't have access, you can still set MainWindow within the main window's constructor.
If you put Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown; into the constructor of the dialog, and add
protected override void OnClosed(EventArgs e) {
base.OnClosed(e);
Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
}
into the dialog class, you don't need to worry about making any changes to the default behaviour of the application. This works great if you want to just snap a login screen into an already-existing app without tweaking the startup procedures.
So you want to show one window, then another, but close down the app when that window is closed? You may need to set the ShutdownMode to OnMainWindowClose and set the MainWindow to Window1, along the lines ok:
Window1 myMainWindow = new Window1();
Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
Application.Current.MainWindow = myMainWindow;
DialogWindow myDialogWindow = new DialogWindow();
myDialogWindow.ShowDialog();
here, do it like this. this will actaully change your main window and will work properly w/o having to change settings of your application object.
make sure to remove the event handler for application startup and to set your StartupUri in your app.xaml file.
public partial class App : Application
{
bool init = false;
protected override void OnActivated(EventArgs e)
{
base.OnActivated(e);
if (!init)
{
this.MainWindow.Closing += new System.ComponentModel.CancelEventHandler(MainWindow_Closing);
init = true;
}
}
void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Window toClose = this.MainWindow;
this.MainWindow = new Window2();
this.MainWindow.Show();
}
}
I have the same issue when i need to disloag a login screen before my main window
In you main window cunstructor add these lines
Application.Current.MainWindow = this;
Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
Resolve the main window or just call var mainWindow = new MainWindow()
Call the loginScreen.Show() or loginScreen.ShowDialog()