How to re-open the closed window? - wpf

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.

Related

WPF Activate two windows

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 }

ShowDialog() behind the parent window

I am using ShowDialog() with WindowStyle = WindowStyle.SingleBorderWindow; to open a modal window in my WPF (MVVM) application, but it lets me navigate to parent window using the Windows taskbar (Windows 7).
I've found an answer here: WPF and ShowDialog() but it isn't suitable for me because I don't need an "always on top" tool window.
Thanks in advance
Try setting the Owner property of the dialog. That should work.
Window dialog = new Window();
dialog.Owner = mainWindow;
dialog.ShowDialog();
Edit:
I had a similar problem using this with MVVM. You can solve this by using delegates.
public class MainWindowViewModel
{
public delegate void ShowDialogDelegate(string message);
public ShowDialogDelegate ShowDialogCallback;
public void Action()
{
// here you want to show the dialog
ShowDialogDelegate callback = ShowDialogCallback;
if(callback != null)
{
callback("Message");
}
}
}
public class MainWindow
{
public MainWindow()
{
// initialize the ViewModel
MainWindowViewModel viewModel = new MainWindowViewModel();
viewModel.ShowDialogCallback += ShowDialog;
DataContext = viewModel;
}
private void ShowDialog(string message)
{
// show the dialog
}
}
I had this problem but as the Window was being opened from a view model I didn't have a reference to the current window. To get round it I used this code:
var myWindow = new MyWindowType();
myWindow.Owner = Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);
You can use: myWindow.Owner = Application.Current.MainWindow;
However, this method causes problems if you have three windows open like this:
MainWindow
|
-----> ChildWindow1
|
-----> ChildWindow2
Then setting ChildWindow2.Owner = Application.Current.MainWindow will set the owner of the window to be its grandparent window, not parent window.
When the parent window makes (and shows) the child window, that is where you need to set the owner.
public partial class MainWindow : Window
{
private void openChild()
{
ChildWindow child = new ChildWindow ();
child.Owner = this; // "this" is the parent
child.ShowDialog();
}
}
Aditionally, if you don't want an extra taskbar for all the children... then
<Window x:Class="ChildWindow"
ShowInTaskbar="False" >
</Window>
Much of the reason for the MVVM pattern is so that your interaction logic can be unit tested. For this reason, you should never directly open a window from the ViewModel, or you'll have dialogs popping up in the middle of your unit tests.
Instead, you should raise an event that the View will handle and open a dialog for you. For example, see this article on Interaction Requests: https://msdn.microsoft.com/en-us/library/gg405494(v=pandp.40).aspx#sec12
The problem seems to be related to Window.Owner, and indeed if you judge by previous knowledge that you might have of the Win32 API and WinForms, a missing owner would be the typical cause of such a problem, but as many have pointed out, in the case of WPF that's not it. Microsoft keeps changing things to keep things interesting.
In WPF you can have a dialog with a specific owner and you can still have the dialog appear in the taskbar. Because why not. And that's the default behavior. Because why not. Their rationale is that modal dialogs are not kosher anymore, so you should not be using them; you should be using modeless dialogs, which make sense to show as separate taskbar icons, and in any case the user can then decide whether they want to see different app windows as separate icons, or whether they want to see them grouped.
So, they are trying to enforce this policy with complete disregard to anyone who might want to go against their guidelines and create a modal dialog. So, they force you to explicitly state that you do not want a taskbar icon to appear for your dialog.
To fix this problem, do the following in the constructor of your view class:
ShowInTaskbar = false;
(This may happen right after InitializeComponent();
This is equivalent to Xcalibur37's answer, though the way I figure things, since WPF forces you to have both a .cs file and a .xaml file, you might as well put things that are unlikely to change in the .cs file.
Add "ShowInTaskbar" and set it to false.
Even if this post is a bit old, I hope it is OK that I post my solution.
All the above results are known to me and did not exactly yield the desired result.
I am doing it for the other googlers :)
Lets say f2 is your window that you want to display on top of f1 :
f2.Owner = Window.GetWindow(this);
f2.ShowDialog();
That's it , I promise it will not disappear !
HTH
Guy

How to make a "popup" (hint, drop-down, popup) window in Winforms?

How can i make, what i will call, a "popup" window" in WinForms?
Since i used my own made-up word "popup", let me give examples of this so-called "popup" window:
a tooltip window (can extend outside the boundaries of its parent form, doesn't appear in the taskbar, is not modal, and doesn't steal focus):
a popup menu window (can extend outside the boundaries of its parent form, doesn't appear in the taskbar, is not modal, and doesn't steal focus):
a drop-down window (can extend outside the boundaries of its parent form, doesn't appear in the taskbar, is not modal, and doesn't steal focus):
A main menu window (can extend outside the boundaries of its parent form, doesn't appear in the taskbar, is not modal, and doesn't steal focus):
Update A popup window not make itself the "active" window when interacted with using a mouse or keyboard (the "owner" window remains the active window):
The attributes that i'm looking for in this mythical "popup" are that it:
can extend outside the boundaries of its parent form (i.e. is not a child window)
doesn't appear in the taskbar (i.e. Window's heuristics of which windows should appear doesn't kick in, nor does it have WS_EX_APPWINDOW extended window style)
is not modal (i.e. doesn't disable its "owner")
doesn't steal focus
is always on-top of of it's "owner"
does not become the "active" window when interacted with (the owner remains active)
Windows applications are already managing to create such windows. How can i do it in a WinForms application?
Related questions
How do i achieve all the above in native code?
How do i create a popup window in Delphi?
i have this native code to show a "popup" window - what P/Invokes are required to perform the same actions in .NET?
i have a set of P/Invoke's in .NET - can i reuse a regular WinForm, overriding certain methods, to achieve the same effect?
i have WinForm that i'm showing as a "popup" by overriding certain methods - is there a built-in Control that can act as a popup for me?
How to simulate a drop-down window in WinForms?
Attempt#1
i tried the Show(onwer) + ShowWithoutActivation method:
PopupForm dd = new PopupForm ();
dd.Show(this);
with PopupForm:
public class PopupForm: Form
{
public PopupForm()
{
InitilizeComponent();
}
private void InitilizeComponent()
{
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.WindowState = FormWindowState.Normal;
this.ShowInTaskbar = false;
}
protected override bool ShowWithoutActivation
{ get { return true; } }
}
Very nearly solved the problem, but then i discovered was reminded of another property of "popup" windows: they do not take focus from their "owner" form become active when interacted with by mouse or keyboard.
You want an owned window. In your main form:
private void showPopup_Click(object sender, EventArgs e)
{
PopupForm popupForm = new PopupForm();
// Make "this" the owner of form2
popupForm.Show(this);
}
PopupForm should look like this:
public partial class PopupForm : Form
{
private bool _activating = false;
public PopupForm()
{
InitializeComponent();
}
// Ensure the popup isn't activated when it is first shown
protected override bool ShowWithoutActivation
{
get
{
return true;
}
}
private const int WM_NCACTIVATE = 0x86;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
protected override void WndProc(ref Message m)
{
// The popup needs to be activated for the user to interact with it,
// but we want to keep the owner window's appearance the same.
if ((m.Msg == WM_NCACTIVATE) && !_activating && (m.WParam != IntPtr.Zero))
{
// The popup is being activated, ensure parent keeps activated appearance
_activating = true;
SendMessage(this.Owner.Handle, WM_NCACTIVATE, (IntPtr) 1, IntPtr.Zero);
_activating = false;
// Call base.WndProc here if you want the appearance of the popup to change
}
else
{
base.WndProc(ref m);
}
}
}
And make sure that PopupForm.ShowInTaskbar = false.
I was curious as to how combobox dropdowns and menus work, so I did some more research.
There are two basic approaches.
Create the popup as an overlapped window, owned by the main window
This method is required if the popup has embedded controls, or if you want the popup to behave as a modeless dialog.
If the user is going to interact with child controls in the popup window, it must receive activation. (So the various techniques for blocking activation, such as handling WM_MOUSEACTIVATE are red herrings.) And when it receives activation, Windows will deactivate the main window. The fix for this is to send a WM_NCACTIVATE message to the parent to update its visual appearance without changing its activation status. This is the approach used by the .Net ToolStrip, and my other answer illustrates it with code.
Create the popup as a child of the Desktop window
This method is used by combobox dropdowns and (I guess) menus, but you can't embed child controls so it's not widely applicable.
The popup is a child window so it doesn't interfere with activation. It is always on top. Mouse capture is used to detect clicks outside the popup and dismiss it.
However, this isn't straightforward to implement. Activation remains with the main application, so it keeps the focus and receives keystrokes. This seems to preclude embedded controls in the popup because they can't receive focus. The combobox handles this by forwarding keystroke messages to its dropdown list. (Note that menus, combobox dropdowns, etc. are all entirely owner-draw in the sense that they have no embedded windows.)
Create your "popup" window as a child window of desktop, then show it without activating it.
hWnd = CreateWindowEx(..., WS_CHILDWINDOW | WS_VISIBLE | WS_BORDER | WS_CLIPSIBLINGS, ..., GetDesktopWindow(), ...);
SetWindowPos(hWnd, HWND_TOPMOST, ..., SWP_NOACTIVATE);
After doing this, your original window remains activated even if you click on the "popuped" window. The "popup" window can have its own children controls. You can click the button on it. But if it is an edit control, you cannot edit it, I don't know why. Maybe because there is already a cursor on your original window, blinking.

WPF - Detect when UserControl is not visible anymore and prompt user

So, I have a class, which goes as follows:
public class EditorUserControl : UserControl
{
public EditorUserControl()
: base()
{
this.IsVisibleChanged += new DependencyPropertyChangedEventHandler(
EditorUserControl_IsVisibleChanged);
}
void EditorUserControl_IsVisibleChanged(
object sender,
DependencyPropertyChangedEventArgs e)
{
if (IsEditing && !((bool)e.NewValue))
{
PressedButton pressedButton = PromptUser(new Buttons[] {
"Save changes to the object you just edited?",
Buttons.Yes,
Buttons.No,
Buttons.Cancel });
if(pressedButton == Buttons.Cancel)
{
CANCELTHETHING();
}
}
}
}
In words - this class is a base for all entity editing controls and when it goes invisible (e.g. window is closed, tab changed etc.) I need to check if the user has made changes and prompt the user whether to save/discard/cancel. The save/discard are easy. The problem is with the third option (and it must be there) - I cannot figure out a way how could I cancel the source event that caused the visibility to change (as there is no way to get to that actual event). Is there a better way to do this functionality (that would not require signing up for all of the possible sources of events)?
I don't think it is possible to cancel the source (event) as you want to.
Consider this line of code - EditorUserControl.Visibility = Visisibility.Hidden;
This will also cause the IsVisibleChanged event to fire, but there is no way to cancel a single line of code.
Your only option is to move the logic inside the IsVisibleChanged event handler to a method that will be called as appropriate by the application. For instance if you close the window then in the window_closing event handler you call the method and if the result is Button.Cancel then you cancel the closing event. If you change tabs then you handle a SelectionChanged event and again call the method and if you need to cancel then you set the selected tab index back to the previous value etc.

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

Resources