I have created a chat application, so when I received a message there is a notification generated so that on clicking notification my chat application should open and I did it using this code below
if (!ApplicationContext.ContactsViewModel.IsWindowOpen)
{
ApplicationContext.CurrentChatView.Dispatcher.Invoke(() =>
{
ApplicationContext.CurrentChatView.WindowState = WindowState.Normal;
ApplicationContext.CurrentChatView.Activate();
});
}
so the problem here is my application is performing all the tasks in the background but instead of appearing in the foreground
I have also tried :
ApplicationContext.CurrentChatView.Topmost=true;
but in this case, the application remains topmost even after clicking on another window.
is there any other alternative to it??
thanks in advance
You should make corrections in your method calling order. Try the following:
if (!ApplicationContext.ContactsViewModel.IsWindowOpen)
{
ApplicationContext.CurrentChatView.Dispatcher.Invoke(() =>
{
if (!Window.IsVisible)
{
Window.Show();
}
if (Window.WindowState == WindowState.Minimized)
{
Window.WindowState = WindowState.Normal;
}
Window.Activate();
Window.Topmost = true; // important
Window.Topmost = false; // important
Window.Focus(); // important
});
}
You can use window.Show() / window.Hide() methods to switch between visible and hidden mode:
private void ShowCurrentWindows()
{
foreach (Window window in Application.Current.Windows)
{
if (!window.IsVisible)
{
window.Show();
}
}
}
private void HideCurrentWindows()
{
foreach (Window window in Application.Current.Windows)
{
if (window.IsVisible)
{
window.Hide();
}
}
}
Related
Can anyone help me understand why my call to dialogservice executes after the CanNavigateAway function has returned its value? (My goal is to warn the user they are about to navigate away from a view without saving their changes. If they click OK, the navigation is allowed. I'm using MVVM Light.
When I step through the code, it does reach the dialog service, but then proceeds to the end of CanNavigateAway before creating the dialog. The CanNavigateAway method is called by OnNavigatingFrom.
public bool CanNavigateAway()
{
if (!changesSaved && Model.IsModified && !continueNavigation)
{
dialogService.ShowMessage("Are you sure you want to continue?",
"Confirmation",
buttonConfirmText: "Continue", buttonCancelText: "Discard",
afterHideCallback: (confirmed) =>
{
if (confirmed)
{
// User has pressed the "confirm" button.
// ...
continueNavigation = true;
}
else
{
// User has pressed the "cancel" button
// (or has discared the dialog box).
// ...
continueNavigation = false;
}
});
return continueNavigation;
}
}
Here is the OnNavigatingFrom method from the MVVM Light Bindable Page class:
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
var navigableViewModel = this.DataContext as INavigable;
if (navigableViewModel != null)
{
if (!navigableViewModel.CanNavigateAway())
{
e.Cancel = true;
}
}
}
I tried this a different way to get the dialog service out of the mix, but showConfirmationDialogAsync still does not seem to execute in time:
public bool CanNavigateAway()
{
continueNavigation = false;
if (!changesSaved && Model.IsModified && !continueNavigation)
{
showConfirmationDialogAsync();
return continueNavigation;
}
private async void showConfirmationDialogAsync()
{
continueNavigation = false;
ContentDialog noSaveConfirmation = new ContentDialog
{
Title = "Warning",
Content = "You have unsaved changes. Are you sure you want to leave this page without saving?",
PrimaryButtonText = "Leave without saving",
SecondaryButtonText = "Stay and finish"
};
ContentDialogResult result = await noSaveConfirmation.ShowAsync();
if (result == ContentDialogResult.Primary)
{
continueNavigation = true;
}
else if (result == ContentDialogResult.Secondary)
{
continueNavigation = false;
}
}
None of the solutions will work if you require a response from the user. The problem is that when the code is inside the navigation event handler, it is running on the UI thread and the user prompt runs asynchronously, so that the UI is free to present the dialog to the user. This however means that the event handler finishes before the user has a chance to respond.
However, you can use a workaround solution. Add a flag bool field like forceNavigation. Then inside the OnNavigatingFrom display the dialog to the user and set Cancel to true right away and display the user the confirmation dialog. If the user says yes, then set forceNavigaiton to true and trigger the navigation manually again. Now it will skip the confirmation part and navigate right away.
protected async override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
//if navigation is forced, skip all logic
if ( !forceNavigation )
{
var navigableViewModel = this.DataContext as INavigable;
if (navigableViewModel != null)
{
e.Cancel = true;
//display the dialog to the user, if he says yes, set
//forceNavigation = true; and repeat the navigation (e.g. GoBack, ... )
}
}
}
When closing my main window(pgLogin) from a child window(pgDashboard), my child window does not want to display at all. In my previous question I set the "ShutdownMode" to "OnExplicitShutdown", so that when I close my main window, the whole application does not shut down. Only thing now is that my application does not shut down, but my child window does not display at all.
Here is my coding from my main window(pgLogin):
Window nextWindow = null;
nextWindow = new pgDashboard();
nextWindow.Owner = this;
this.Hide();
nextWindow.Show();
And my child window(pgDashboard):
public static T IsWindowOpen<T>(string name = null) where T : Window
{
var windows = Application.Current.Windows.OfType<T>();
return string.IsNullOrEmpty(name) ? windows.FirstOrDefault() : windows.FirstOrDefault(w => w.Name.Equals(name));
}
private void HAZEDashboard_Loaded(object sender, RoutedEventArgs e)
{
var credentials = this.Owner as pgLogin;
credentials.txtEmailAddress.Text.ToString();
var window = IsWindowOpen<pgLogin>();
if (window != null)
{
window.Close();
}
}
Any idea why this could be happening?
EDIT: Just did a test, and I can see that when I close the main window, my child window also closes for some reason, because when I try to call this.Show(); on my child window, it gives me this error:
Cannot set Visibility or call Show, ShowDialog, or WindowInteropHelper.EnsureHandle after a Window has closed.
EDIT 2: I think the problem might be caused because I set the main window(pgLogin) as the owner of the child window(pgDashboard)?
I figured it out. This is what I did:
My main window(pgLogin):
Window nextWindow = null;
nextWindow = new pgDashboard();
App.Current.MainWindow = nextWindow;
nextWindow.Show();
My child window(pgDashboard):
public static T IsWindowOpen<T>(string name = null) where T : Window
{
var windows = Application.Current.Windows.OfType<T>();
return string.IsNullOrEmpty(name) ? windows.FirstOrDefault() : windows.FirstOrDefault(w => w.Name.Equals(name));
}
private void HAZEDashboard_Loaded(object sender, RoutedEventArgs e)
{
var window = IsWindowOpen<pgLogin>();
if (window != null)
{
var credentials = window.txtEmailAddress.Text.ToString();
window.Close();
}
}
I did not set the owner of the child window(pgDashboard) to pgLogin, because when I close the main window (pgLogin), all of the windows that the main window owns, closes as well.
I'm trying to close my Main Window from a child window in my WPF application. The problem is, once I try to 'close' the main window, my whole application closes.
Here is my coding from my main window(pgLogin):
Window nextWindow = null;
nextWindow = new pgDashboard();
nextWindow.Owner = this;
this.Hide();
nextWindow.Show();
And my child window(pgDashboard):
public static T IsWindowOpen<T>(string name = null) where T : Window
{
var windows = Application.Current.Windows.OfType<T>();
return string.IsNullOrEmpty(name) ? windows.FirstOrDefault() : windows.FirstOrDefault(w => w.Name.Equals(name));
}
private void HAZEDashboard_Loaded(object sender, RoutedEventArgs e)
{
var credentials = this.Owner as pgLogin;
credentials.txtEmailAddress.Text.ToString();
var window = IsWindowOpen<pgLogin>();
if (window != null)
{
window.Close();
}
}
Is there a way to close the main window without hiding it and still keeping open my child window?
Goto to the Applications App.xaml and Change the "ShutdownMode", for example to "OnExplicitShutdown".
The default is ShutdownMode="OnMainWindowClose" which results in the behaviour you described.
I'm setting up a simple WPF application, which looks at its command-line arguments to determine what kind of window should be shown next. When that's determined, I show the next window by calling new ApplicationWindow(), set the content, and call Show(). The problem is that the MainWindow instance seems to have "application control" - i.e. when it closes, so does everything else.
It goes like this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
TopBar.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF1975DD"));
this.ContentRendered += MainWindow_ContentRendered;
this.OperationModeSet += MainWindow_OperationModeSet;
}
[STAThread]
private void MainWindow_ContentRendered(object sender, EventArgs e)
{
Thread worker = new Thread(new ThreadStart(this.ParseCommandLineArgs));
worker.SetApartmentState(ApartmentState.STA);
worker.Start();
}
[STAThread]
public void ParseCommandLineArgs()
{
Thread.Sleep(3000);
string[] args = Environment.GetCommandLineArgs();
if (args.Any(item => item == "--server" || item == "-s"))
{
SetOperationMode(OperationMode.Server);
Dispatcher.BeginInvoke(new Action(delegate()
{
this.CloseWindow();
}));
}
else
{
SetOperationMode(OperationMode.Client);
Dispatcher.BeginInvoke(new Action(delegate()
{
this.CloseWindow();
}));
}
}
[STAThread]
private void SetOperationMode(OperationMode mode)
{
OperatingMode = mode;
if (OperationModeSet != null)
{
OperationModeSet(this, new OperationModeSetEventArgs(mode));
}
}
[STAThread]
private void MainWindow_OperationModeSet(object sender, OperationModeSetEventArgs e)
{
AppWindow window = new AppWindow();
if (e.Mode == OperationMode.Client)
{
this.CloseWindow();
window.Content = new ClientPage();
}
else if (e.Mode == OperationMode.Server)
{
this.CloseWindow();
window.Content = new ServerPage();
}
window.Show();
}
}
These methods get called in the order I've put them here, through various events. I've omitted a few fields and properties.
The problem is that when this MainWindow closes, so does window - the instantiated ApplicationWindow. I assume this is because the MainWindow created it.
However, I do want to be able to close the MainWindow and continue with another window as the "main" window - so how can I decouple the instantiated ApplicationWindow from its parent MainWindow so it continues on?
I've seen setting Application.MainWindow in App.xaml changes the main window - but I have no reference to the instantiated window that I can put into a static XAML file.
Why are you parsing the command line args in your MainWindow?
You could just remove the StartupUri in the App.xaml and override the OnStartup method. Then you can use StartUpArgs to decide which operating mode you want.
In App.xaml.cs
protected override void OnStartup(StartupEventArgs e)
{
// Decide which window to show here
// Add bounds checks etc.
if (e.Args[0] == "-s")
{
var window = new ServerPage();
window.Show();
}
else
{
var window = new ClientPage();
window.Show();
}
Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
base.OnStartup(e);
}
What I think you could do (now there are better options I'm sure...) is instead of creating a new window in your main program, move your other code into a new project and in your main project, launch it as a new process with Process.Start(...).
I've only ever seen code that used this though, never written it from scratch myself. But I would take a look at this page from the MDSN and pages related to it.
Excuse the lack of example code to help you, this is just at the edge of my knowledge and I'd hate to give you incorrect code.
I need to close a popup window which has been loaded by a parent window.
This popup window is a Documentviewer window in my webapp.
I need to close this viewer by clicking a logout button which is in master page.
My code:
public string MySession //server side code
{
get
{
if (Session["RegID"] != null)
{
return Session["RegID"].ToString();
}
else
{
return "";
}
}
}
//client side code
$(window).load(function() {
Start();
});
function Start()
{
timedCount();
var t=setTimeout("Start()",10000);
}
function timedCount()
{
/*var out="<%=Session["RegID"]%>";*/
var out='<%=MySession%>';
if(out!="")
{
alert(out);
}else
{
window.close();
}
}
Server code is executed at very first time only.
My target is to close the popup if it is opened when user logs out.
You probably have something like this on your parent page:
window.open(...);
If you change this to:
var popup = window.open(...);
then at any time you can close it by coding:
popup.close();
http://jsfiddle.net/pimvdb/bjkNx/1/
Put your popup window in global variable:
<script>
var popupWindow;
function openw(url) {
popupWindow = window.open(url, "popup", "");
}
function closew() {
if (popupWindow) {
popupWindow.close();
}
}
</script>
open<br />
close