WPF Activate two windows - wpf

I've got two windows which Need to be shown together. Problem is, when they are in the back and the user opens one of these via alt-tab, the other window is still in the back
By now, I managed to do this with
private void Window_Activated(object sender, EventArgs e)
{
OtherWindow.Activate();
this.Activate();
}
in both windows, but it creates Kind of a flickering and I was wondering if there is a "cleaner" way to achieve this
Long Story short: when one window is activated, the other one should be too

See Window Owner property, if your 2 window have same Owner or one window is owner to second one, then activating one of them should be activate another also.
Window W = new Window() { Owner=this }

Related

ALT-TAB always activates main window in WPF app with multiple owned windows

On Windows 7, .NET 4.0 I have a problem that can be reproduced by copying the following code into a blank WPF application generated by Visual Studio:
public MainWindow()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
new Window() { Title = "Test", ShowInTaskbar = false, Owner = this }.Show();
}
Run app
Activate secondary window
Alt-Tab to other running application
Use mouse to activate our WPF app in taskbar
Now the WPF app is active again, with the secondary window activated and the main window deactivated, which is the expected (and desired) behavior.
Now do this instead (only step 4 differs):
Run app
Activate secondary window
Alt-Tab to other running application
Alt-Tab back to our WPF app
The WPF app is active again, but now the main window is activated.
Adding this code
private void Application_Activated(object sender, EventArgs e)
{
Windows[1].Activate();
}
to App.xaml.cs does not solve the problem because now in the second case both windows are activated. Also, clicking the secondary window does not deactivate the main window. I have to click the (already activated) main window and the secondary window again to achieve this.
How can I avoid this (only the secondary window should be active in both cases)?
CodeProject actually addresses this issue here, hope this is what you're looking for.
Combine with a post from Tamil Khason and in theory you can override the OnFocus event on a global level so that every time a window is on focus, that becomes the "main window" which will then be the target of ALT+TAB.
based on THIS solution the following code can maybe (not tested jet) also do the trick
protected override void OnStartup(StartupEventArgs e)
{
EventManager.RegisterClassHandler(typeof(Window), Window.LoadedEvent, new RoutedEventHandler(WindowLoaded));
base.OnStartup(e);
}
void WindowLoaded(object sender, RoutedEventArgs e)
{
Window w = sender as Window;
if (w != null)
{
// this part works in my case very well
w.Owner =Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);
}
}

WPF - Toggle Visibility of multiple windows

i will first explain the UI of my WPF App.
I have created a window which contains many buttons which is always visible to the user(lets call it main window), each button will open a new window relevant to the task. what i want done is that whenever a button is clicked, the main window should be hidden(visibility : collapsed) and the new window should be shown. This second window will also contain a button which will hide the second window and show back the main window.
also the second window which will be opening will have different dimensions as per the command associated with it so i will be having different windows for eaach
TLDR i want to be able to switch between multiple windows such that only one window is visible at one time, how do i manage the switching between multiple windows ??
Note : I can show the second window from main window but what about showing main from the second window....can't get it....or if anyone can show me a different approach to implement this : other than multiple windows
Also, this is an extension to the UI, i want to show the buttons in this crystalised sort of look like on this page : http://postimage.org/image/4yibiulsh/
can anyone direct me to a proper implementation, i have been through many sites and also tried to create these through blend but i just am not a UI Person....pls need help on this
Thanks in advance.
I would create a "Window manager" which will subscribe to the changes of opening/closing.
In this case you don't have to overload Window classes.
Example (worked for me).
public class WindowsManager
{
static readonly List<Window> Windows=new List<Window>();
public static T CreateWindow<T>(T window) where T:Window
{
Windows.Add(window);
window.Closed += WindowClosed;
window.IsVisibleChanged += WindowIsVisibleChanged;
return window;
}
static void WindowIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var mainWindow = Application.Current.Windows.OfType<MainWindow>().Single();
mainWindow.Visibility = Equals(e.NewValue, true) ? Visibility.Hidden : Visibility.Visible;
}
static void WindowClosed(object sender, System.EventArgs e)
{
var window = (Window) sender;
window.Closed -= WindowClosed;
window.IsVisibleChanged -= WindowIsVisibleChanged;
Windows.Remove(window);
}
}
How to use:
private void button1_Click(object sender, RoutedEventArgs e)
{
WindowsManager.CreateWindow(new Child1()).Show();
}
private void button2_Click(object sender, RoutedEventArgs e)
{
WindowsManager.CreateWindow(new Child2()).Show();
}
So, when the child window will close, WindowsManager will be notified about this and will update visibility for the main window
UPD1.
added line to unscubscribe from VisibleChanged
You can use several approaches for that.
To easy switch back to main Window: inject a reference of your MainWindow to your SecondWindow (or any other Window you want to display) and in the Closing Event of that Window you set the Visibility of the MainWindow back to Visible.
Have you also considered keeping everything in the same Window but having different Panels that you set Visible and Invisible? That could have the same effect but it's less complicated...
Hope that helps...

How to re-open the closed window?

i've seen so many samples that in order to open closed window i should hide the window in closing event, but this is not fair for me if i close window in middle of my work and again open same window it showing me content where i left because i'm hiding window previously. So how can i start freshly my window after closed or hide the window.
currently i'm calling winload method which is to show fresh window after calling the show method of a hide window.
private PurgeData data=new PurgeData();
private void MenuPurgeData_Click(object sender, RoutedEventArgs e)
{
try
{
if (PurgeData == null)
{
PurgeData = new PurgeData();
PurgeData.Show();
}
else
{
PurgeData.WinLoad();
PurgeData.Show();
}
}
Thanks,
#nagaraju.
If you want the behaviour of hide/show, you should not call Window.Close() on the window at all, but hide it by calling Window.Hide(). If the user has closed it though and a close is unavoidable, you can try the following. Override OnClosing inside the Window and set e.Cancelled to true, then call .Hide(). This should allow the window to be hidden/shown even if the user closes the window.
// Disclaimer, untested!
protected override void OnClosing(CancelEventArgs e)
{
e.Cancel = true; // cancels the window close
this.Hide(); // Programmatically hides the window
}
EDIT:
Ok I've now read your question properly ;-)
So how can i start freshly my window after closed or hide the window.
When you re-show the window using the above, it will of course be the same instance as the one that was previously hidden, hence will have the same data and state. If you want completely new contents you need to create a new Window() and call Window.Show() on that. If you hide/show as above then you'll get the window back in exactly the same state before it was hidden.
Are you using the MVVM pattern in your WPF application? If so, you could try the following. By having all the data in your ViewModel and bound to by the View (ie: no business logic or data in the code behind of the Window), then you could invoke a method on the ViewModel to reset all data when the window is shown. Your bindings will refresh and the window state will be reset. Note this will only work if you have correctly followed MVVM and bound all elements on the main form to ViewModel properties (including sub controls).
Best regards,
It really depends on the structure of your app. Since you're not maintaining state, you only need to save the actual type of window that was closed. Depending on what type of window you're using, you can assign it an ID (e.g. in its Tag property) so that it can be recognized later. You can then push this ID during the Closing event in a Stack. Then, if the user reopens it, pop the stack to get the ID and check what window that corresponds to. You can then reopen that window.
Of course, Stack is just one data structure and it may or may not be suitable for you. Using a Stack means that user can reopen all the past windows they closed, but maybe you might just want the one window instead.
Edit - basic code:
//create an enum to make it easy to recognise the type of window that was open
enum WindowType { Profile, Settings };
//create a stack to hold the list of past windows
Stack<WindowType> pastWindows = new Stack<WindowType>();
//give the window type a particular id
profileWindow.Tag = WindowType.Profile;
//open the window
profileWindow.Show();
//in the closing event, if you want the user to be able to reopen this window, push it to the stack
protected override void OnClosing(CancelEventArgs e)
{
pastWindows.Push(WindowType.Profile); //or whatever type it was
base.OnClosing(e);
}
//to reopen the last window
void ReopenLastWindow()
{
WindowType lastType = pastWindows.Pop();
switch(lastType)
{
case WindowType.Profile:
profileWindow.Show();
break;
case WindowType.Settings:
settingsWindow.Show();
break;
default:
break;
}
}
this.Opacity = 0
to "close the window"
this.Opacity = 1
to "re-open it"
A remark concerning the Hide() method: from another class, the window will in fact be considered as closed and the code will continue after a ShowDialog() method usage. Using the "Opacity" property overrides the problem.

My application loses focus when a window is closed

I have a simple two forms, one that contains a grid and a button. When I click the button, my application starts doing a long operation. While it is working, I show another form that contains a progress bar
I open it like this:
_busyWindow.ShowDialog();
And defined
public partial class BusyWindow : DevExpress.XtraEditors.XtraForm
{
public BusyWindow()
{
InitializeComponent();
}
private void BusyWindow_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
e.Cancel = true; // this cancels the close event.
}
}
When the operation is finished, I hide the form like this
if (ended)
_busyWindow.Hide();
It works fine. The problem is that when I close the second form (same closing code), it also closes fine but my main GUI loses the focus. For example, if I have the Firefox opened behind the application, then the Firefox gets the focus.
This only happens when I close the second form when the busyWindow has been opened, and no when it hasn't (ie, if I open the form, I close it without clicking on the button, then the main GUI doesn't lose the focus).
Do you know what is happening or where could I try to search?
There could be two possible solutions to enable you to keep focus on your main window:
//Edited: Main Window in the below example would be the window with Grid and Button.
Since you are showing the busy window via ShowDialog() try setting the owner of the window by this: _busyWindow.ShowDialog(this);. I had earlier faced a similar problem and this worked for me. Since you specify the owner of the busyWindow, when it closes it would put the focus back on its owner,i.e. your main window
In case the above technique doesnt work (it should, as it worked for me), you could try to pass the reference of the main window to the busyWindow and then on its close set the focus of the main window. Sample:
_busyWindow.MyMainWindow = this; //MyMainWindow references mainWindow of your app
_busyWindow.ShowDialog();
And the following at the FormClosing of busyWindow:
private void BusyWindow_FormClosing(object sender, FormClosingEventArgs e)
{
this.Hide();
e.Cancel = true; // this cancels the close event.
MainWindow.Focus();
}
See if it works. The first solution should work.
Hope it helps.
Thanks & Happy Windowing!
Just set child's window Owner = null before closing it

WPF ComboBox DropDown part appears in the wrong place

I put several ComboBoxes on a XAML window. When I expand any of them, the DropDown part appears on the upper left corner of the screen.
I use Visual Studio 2008 C# Express. I don't remember this phenomenon when I used Visual Studio 2008 (Trial Version), though I use the same FrameWork (3.5).
It seems to be a bug.
Workaround:
Use Window.Show() instead with a custom logic to simulate the ShowDialog() behavior.
This appears to be a bug in WPF. In my case, I was trying to open a window in the Loaded event of another window. To get around this, I set a timer up to fire, then used a delegate to open the window (cannot open the window in a timer event because the calling thread that opens a window must be STA).
Edit - timer isn't necessary - didn't see the answer above just queue it on the dispatcher...
private delegate void DelegateOpenWindow();
private DelegateOpenWindow m_DelegateOpenWindow;
private Timer loginTimer = new Timer(200);
private void MainWindow1_Loaded(object sender, RoutedEventArgs e)
{
// create delegate used for asynchronous call
m_DelegateOpenWindow= new DelegateOpenWindow(this.OpenWindow);
// start a timer to fire off the open window.
loginTimer.Elapsed += loginTimer_Elapsed;
loginTimer.Enabled = true;
}
void loginTimer_Elapsed(object sender, ElapsedEventArgs e)
{
loginTimer.Enabled = false;
this.Dispatcher.BeginInvoke(m_DelegateOpenWindow);
}
void OpenWindow()
{
MyWindow w = new MyWindow();
w.Owner = this;
w.ShowDialog();
}
I started observing this (and other strange behavioral quirks) yesterday when I tried to "tweak" window sizes, shapes, colors, and invoke a log-on dialog from the Window.Loaded event handler. I had been doing this just fine in each of a dozen+ individual "MVVM" pattern apps. Yesterday, I decided to move this from each app's code behind into a consolidated code-behind base class, since the pre-processing had become common in all those apps. When I did, the drop-downs in two ComboBoxes in the log-in dialog suddenly appeared in the upper left corner of my screen. I seem to have "solved" it by using the following technique (your mileage may vary):
protected void WindowBaseLoadedHandler(object sender, RoutedEventArgs e)
{
...non-essential lines of code removed...
if (DataContext != null)
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
{
/*----------------------------------------------------------------------
* Do we have a View Model? If so, perform standard VM Initialization...
*---------------------------------------------------------------------*/
this.IsEnabled = false;
LoginDlg loginDlg = new LoginDlg();
loginDlg.ShowDialog();
if (!loginDlg.Success)
{
/*-----------------------------------
* Log on failed -- terminate app...
*----------------------------------*/
...termination logic removed...
}
this.IsEnabled = true;
}));
}
WindowBaseLoadedHandler is the Loaded event handler. LoginDlg is a WPF app with a dialog containing two ComboBoxes.
Recap: After I consolidated the code into the Loaded event handler of the base class the ComboBox's drop down lists appeared in the upper left corner of my screen. Once I wrapped the logic into the Dispatcher.BeginInvoke call, the appropriate ComboBox behavior returned with lists below the current item.
I suspect WPF needs the application to return from the Loaded event to complete the layout system's initialization. That doesn't fully explain why it worked before, but I'll have to queue up my desire to hunt that "why" down for some rainy day in the future and celebrate overcoming the latest obstacle for today.
In any event, I hope someone finds this of use.
I'm using the latest .Net 4.5 and WPF framework and I still have this problem. One thing I noticed is that it only happen when there's an attached debugger. When the debugger is not attached, everything works fine.
I had the same problem on Visual Studio 2019.
Using window.Show() can help but it can ruin your design.
The solution is to open the window asynchronously.
var yourDialog= new YourDialog();
yourDialog.Owner = this;
TaskCompletionSource<bool?> completion = new TaskCompletionSource<bool?>();
this.Dispatcher.BeginInvoke(new Action(() =>
completion.SetResult(yourDialog.ShowDialog())));
bool? result = await completion.Task;
You can also create a more elegant solution by making the extension method:
public static class AsyncWindowExtension
{
public static Task<bool?> ShowDialogAsync(this Window self)
{
if (self == null) throw new ArgumentNullException("self");
TaskCompletionSource<bool?> completion = new TaskCompletionSource<bool?>();
self.Dispatcher.BeginInvoke(new Action(() => completion.SetResult(self.ShowDialog())));
return completion.Task;
}
}
And you can use it like this:
await dlgReview.ShowDialogAsync();
It’s a bug in WPF (not the only one, I'm afraid). It happened when I opened another window in the Loaded Event, something like:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Window selectionWindow = new SelectionWindow();
bool? result = selectionWindow.ShowDialog();
if (result == true)
RecordChanged();
}
I already found a workabout.

Resources