When I press on the hardware back button in my uwp app, the app closes. I use the hamburger interface from Template 10.
I added the following code in the app.xaml.cs and in het schell.xaml.cs but when I press back it says that the parameter canGoBack is false and closes the app.
public Shell(INavigationService navigationService)
{
Instance = this;
InitializeComponent();
// setup for static calls
Window = WindowWrapper.Current();
MyHamburgerMenu.NavigationService = navigationService;
// any nav change, reset to normal
navigationService.FrameFacade.Navigated += (s, e) =>
BusyModal.IsModal = LoginModal.IsModal = false;
SystemNavigationManager.GetForCurrentView().BackRequested += Shell_BackRequested;
}
private void Shell_BackRequested(object sender, BackRequestedEventArgs e)
{
MyHamburgerMenu.NavigationService.GoBack();
}
This is how you should handle the BackRequested event for a default implementation:
SystemNavigationManager.GetForCurrentView().BackRequested += (sender, e) =>
{
if (!e.Handled && Frame.CanGoBack)
{
e.Handled = true;
AppFrame.GoBack();
}
};
Remember that for CanGoBack to be true you should call first a Frame.Navigate()
If there are frames in the Frame.BackStack, then CanGoBack will be true.
Related
I implement a form for handle excel file when click button "Start".
Event click Start button:
private void btnImport_Click(object sender, EventArgs e)
{
showFormSelectLanguage();
if (CheckSheetFile() == true) {
using (WaitingForm frm = new WaitingForm(handleExcel))
{
frm.ShowDialog(this);
}
var dialogMessage = new DialogMessage();
dialogMessage.ShowDialog(this);
} else
{
ShowDialogNotFoundSheet();
}
}
showFormSelectLanguage method display dialog for select language:
private void showFormSelectLanguage()
{
var formSelectLanguage = new FormSelectLanguage();
formSelectLanguage.ShowDialog(this);
}
ShowDialogNotFoundSheet function for check sheet excel exist:
private void ShowDialogNotFoundSheet()
{
var dialogNotFoundSheet = new DialogNotFoundSheet();
dialogNotFoundSheet.setTextContent("Not found sheet");
dialogNotFoundSheet.ShowDialog(this);
}
Event click confirm select language button at Select language form:
private void btnConfirmLanguage_Click(object sender, EventArgs e)
{
//close dialog
this.Close();
}
Event click Close button for close DialogNotFoundSheet form:
private void btnCloseDialogNotFoundSheet_Click(object sender, EventArgs e)
{
this.Close();
}
CheckSheetFile method:
private bool CheckSheetFile()
{
var isCorrectFile = false;
try
{
xlWorkBook = xlApp.Workbooks.Open(txtFilePath.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read);
var xlWorkBook1 = xlWorkBook.Sheets["SheetName"];
isCorrectFile = true;
}
catch (Exception e)
{
return false;
}
return isCorrectFile;
}
Issue:
When I click Close button at DialogNotFoundSheet form. Then FormSelectLanguage from still display. It repeats. How can resolve it?
Expected 2 forms can close
Thanks!
Update:
All References btnImport_Click:
UI:
I don't exactly know what you did with btnImport_Click, but if your purpose is to disable the function of a button at a time and to enable it at another time, actually you don't have to register or unregister the click event, you can simply set button's Enabled propety.
//btnImport.Click += btnImport_Click;
btnImport.Enabled = true;
//btnImport.Click -= btnImport_Click;
btnImport.Enabled = false;
My guess of the reason of this loop is that you have called += btnImport_Click many times, but -= btnImport_Click is never (or less) run.
For instance if you do:
btnImport.Click += btnImport_Click;
btnImport.Click += btnImport_Click;
Each time btnImport is clicked, btnImport_Click will get invoked twice.
I am using AxMSTSCLib to develop a Windows App for creating RDP connections.
The steps listed below caused my remote desktop display disappear:
Start an RDP connection with full-screen mode
Click "restore down" button from connection bar
Click "maximize" button again to re-enter full-screen mode
Click "minimize" button
Then my app disappears, I can't see it in taskbar (but still be listed / running in taskmanager)
If I skip steps 2 & 3, it won't disappear when I click "minimize" button from connection bar, it's really weird.
I post some part of my code here, hope anyone can help me to find out the problem.
public partial class RdpShowForm : Form
{
public AxMSTSCLib.AxMsRdpClient9NotSafeForScripting oRemote;
public RdpShowForm()
{
InitializeComponent();
oRemote = new AxMSTSCLib.AxMsRdpClient9NotSafeForScripting();
((System.ComponentModel.ISupportInitialize)(this.oRemote)).BeginInit();
oRemote.Dock = System.Windows.Forms.DockStyle.Fill;
oRemote.Enabled = true;
oRemote.Name = "WindowsVM";
this.Controls.Add(oRemote); // Controls contains 'panel1' and 'oRemote'
((System.ComponentModel.ISupportInitialize)(this.oRemote)).EndInit();
oRemote.CreateControl();
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
}
private void RdpShowForm_Load(object sender, EventArgs e)
{
NewRdpConnectionInstance();
}
private void NewRdpConnectionInstance()
{
oRemote.Server = 'xxx';
...
oRemote.FullScreen = true;
oRemote.AdvancedSettings7.DisplayConnectionBar = true;
oRemote.AdvancedSettings7.ConnectionBarShowMinimizeButton = true;
oRemote.AdvancedSettings7.ConnectionBarShowRestoreButton = true;
oRemote.OnConnected += rdpClient_OnConnected;
oRemote.OnLeaveFullScreenMode += rdpClient_OnLeaveFullScreenMode;
oRemote.Connect();
oRemote.Show();
oRemote.Focus();
}
private void rdpClient_OnConnected(object sender, EventArgs e)
{
this.panel1.Visible = false;
this.Visible = false;
}
private void rdpClient_OnLeaveFullScreenMode(object sender, EventArgs e)
{
this.Visible = true;
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_SYSCOMMAND)
{
if (m.WParam.ToInt32() == MAXIMIZE)
{
this.Visible = false;
oRemote.FullScreen = true;
oRemote.Show();
}
}
base.WndProc(ref m);
}
}
I've tried some methods, but none of them worked.
oRemote.Bounds = Screen.PrimaryScreen.WorkingArea;
oRemote.IsAccessible = true;
this.ShowInTaskbar = true;
or
this.Visible = ture; // do not hide the main form
or
if (m.WParam.ToInt32() == MAXIMIZE)
{
oRemote.FullScreen = true;
oRemote.Show();
oRemote.Update();
oRemote.Refresh();
}
So far, the only solution that came into my mind is to disable the restore button, like this:
oRemote.AdvancedSettings7.ConnectionBarShowRestoreButton = false;
This way isn't fix the problem, just avoid the issue to be triggered.
I would appreciate any help.
Since AxMSTSCLib has a restore down issue, I turn to use a form to handle its fullscreen mode. In this way, I can get extensive control over full-screen mode behavior, write code to tell the container what to do when the restore down button is called.
// enable container-handled full-screen mode
oRemote.AdvancedSettings7.ContainerHandledFullScreen = 1;
Then, customize OnRequestGoFullScreen, OnRequestLeaveFullScreen, OnRequestContainerMinimize.
oRemote.OnRequestGoFullScreen += corey_OnRequestGoFullScreen;
oRemote.OnRequestLeaveFullScreen += corey_OnRequestLeaveFullScreen;
oRemote.OnRequestContainerMinimize += corey_OnRequestContainerMinimize;
private void corey_OnRequestGoFullScreen(object sender, EventArgs e)
{
// set the form to fullscreen
}
private void corey_OnRequestLeaveFullScreen(object sender, EventArgs e)
{
// set the form back to non-fullscreen mode
}
private void corey_OnRequestContainerMinimize(object sender, EventArgs e)
{
// minimize the form
}
The method I posted here can be a workaround to this issue.
I'm using AppWindow to create multiple windows for the app, and I want the user to be able to make the windows full screen, but ApplicationView.TryEnterFullScreenMode doesn't work, it returns false all the time when used in an AppWindow.
Sample code from Microsoft Docs:
private void ToggleFullScreenModeButton_Click(object sender, RoutedEventArgs e)
{
var view = ApplicationView.GetForCurrentView();
if (view.IsFullScreenMode)
{
view.ExitFullScreenMode();
}
else
{
view.TryEnterFullScreenMode(); // Returns false in an AppWindow
}
}
How do you make an AppWindow enter full screen mode?
For AppWindow you should use AppWindowPresenter.RequestPresentation and pass AppWindowPresentationKind.FullScreen as parameter.
The solution I came up with (based on this answer) handles exiting full screen mode using:
The original button.
The back to window button in the title bar.
The escape key.
XAML:
<Button x:Name="ToggleFullScreenButton" Text="Full screen mode" Click="ToggleFullScreenButton_Click" />
Code behind:
public AppWindow AppWindow { get; } // This should be set to the AppWindow instance.
private void ToggleFullScreenButton_Click(object sender, RoutedEventArgs e)
{
var configuration = AppWindow.Presenter.GetConfiguration();
if (FullScreenButton.Text == "Exit full screen mode" && _tryExitFullScreen())
{
// Nothing, _tryExitFullScreen() worked.
}
else if (AppWindow.Presenter.RequestPresentation(AppWindowPresentationKind.FullScreen))
{
FullScreenButton.Text = "Exit full screen mode";
_ = Task.Run(async () =>
{
await Task.Delay(500); // Delay a bit as AppWindow.Changed gets fired many times on entering full screen mode.
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
AppWindow.Changed += AppWindow_Changed;
this.KeyDown += Page_KeyDown;
});
});
}
}
private bool _tryExitFullScreen()
{
if (AppWindow.Presenter.RequestPresentation(AppWindowPresentationKind.Default))
{
FullScreenButton.Text = "Full screen mode";
AppWindow.Changed -= AppWindow_Changed;
this.KeyDown -= Page_KeyDown;
return true;
}
return false;
}
// handles the back-to-window button in the title bar
private void AppWindow_Changed(AppWindow sender, AppWindowChangedEventArgs args)
{
if (args.DidSizeChange) // DidSizeChange seems good enough for this
{
_tryExitFullScreen();
}
}
// To make the escape key exit full screen mode.
private void Page_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Escape)
{
_tryExitFullScreen();
}
}
I have a problem with the hardware back button on windows phone 10 that does not work when the default page is the page BackgroundMusic.
App.cs
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
rootFrame.Navigated += RootFrame_Navigated;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
// Register a handler for BackRequested events and set the
// visibility of the Back button
SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
rootFrame.CanGoBack ?
AppViewBackButtonVisibility.Visible :
AppViewBackButtonVisibility.Collapsed;
}
if (e.PrelaunchActivated == false)
{
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(BackgroundMusic), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
}
private void RootFrame_Navigated(object sender, NavigationEventArgs e)
{
// Each time a navigation event occurs, update the Back button's visibility
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
((Frame)sender).CanGoBack ?
AppViewBackButtonVisibility.Visible :
AppViewBackButtonVisibility.Collapsed;
}
private void OnBackRequested(object sender, BackRequestedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
if (App.DetectPlatform() == Platform.WindowsPhone)
{
HardwareButtons.BackPressed += new EventHandler<BackPressedEventArgs>((s, a) =>
{
if (rootFrame.CanGoBack)
{
rootFrame.GoBack();
a.Handled = true;
}
});
}
else if (App.DetectPlatform() == Platform.Windows)
{
if (rootFrame.CanGoBack)
{
e.Handled = true;
rootFrame.GoBack();
}
}
}
public static Platform DetectPlatform()
{
bool isHardwareButtonsAPIPresent = ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons");
if (isHardwareButtonsAPIPresent)
{
return Platform.WindowsPhone;
}
else
{
return Platform.Windows;
}
}
public static MediaElement GlobalMediaElement
{
get { return Current.Resources["MyPlayer"] as MediaElement; }
}
private void mediaended(object sender, RoutedEventArgs e)
{
var AppMediaElement = App.GlobalMediaElement;
AppMediaElement.Position = TimeSpan.Zero;
AppMediaElement.Play();
}
BackgroundMusic.cs
const string soundTrackToken = "soundtrack";
int flag = 1;
public BackgroundMusic()
{
this.InitializeComponent();
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
//navigationHelper.OnNavigatedTo(e);
mainFrame.Navigate(typeof(MainPage));
if (StorageApplicationPermissions.FutureAccessList.ContainsItem(soundTrackToken))
{
StorageFile audioFile = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(soundTrackToken);
if (audioFile != null)
{
await StartAudio(audioFile);
}
}
}
How to handle it?
Note:
- When the default page is MainPage, the hardware back button to work. But when the default page is the BackgroundMusic page, hardware back button does not work
- BackgroundMusic page is a page for background music (there is also a play and stop button) on the application.
Can you try this:
Under
SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
put
HardwareButtons.BackPressed += OnBackRequested:
then delete this inside OnBackRequested
HardwareButtons.BackPressed += new EventHandler<BackPressedEventArgs>((s, a) =>
{
The explanation is that you need to register the event handler upfront. In your current code, you only handles software back button. When it is clicked and knowing that it is Phone platform, then you register a new event handler. So, what I suggested you to do is register the handler the same as the software back button up front, so it handles the same behavior, and you don't need to add new event handler if it is a phone later on.
First of all, when on windows phone you handled hardware back button like this:
if (App.DetectPlatform() == Platform.WindowsPhone)
{
HardwareButtons.BackPressed += new EventHandler<BackPressedEventArgs>((s, a) =>
{
if (rootFrame.CanGoBack)
{
rootFrame.GoBack();
a.Handled = true;
}
});
}
This is not right, it is like to handle the back button twice, two items in the BackStack of the rootFrame will be removed when back button is pressed on mobile. You can change this code like this:
if (App.DetectPlatform() == Platform.WindowsPhone)
{
if (rootFrame.CanGoBack)
{
rootFrame.GoBack();
e.Handled = true;
}
}
Secondly, in the OnNavigatedTo event of your BackgroundMusic, I don't know what is your mainFrame, if this is the Frame inside the BackgroundMusic page, then it can be navigated to MainPage, the BackStack of rootFrame will have no items. And if this mainFrame is exactly the rootFrame, navigation will failed when it is on the OnNavigatedTo event, the items' count BackStack of rootFrame still remains to be 0.
So if you want to use rootFrame to navigate to MainPage when the default Page of rootFrame is BackgroundMusic, you can in the Loaded event navigate to MainPage for example like this:
private void BackgroundMusic_Loaded(object sender, RoutedEventArgs e)
{
var status = this.Frame.Navigate(typeof(MainPage));
}
I want to handled the backpress button in windows phone 8.1 app.I want whenever backpress is pressed navigate to previous page but when backpress is pressed at the second page(after the mainpage) i want the app to exit or asked to exit.
i am using this code to navigate
Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
public bool Handled { get; set; }
private void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
{
Frame frame = Window.Current.Content as Frame;
if (frame == null)
{
return;
}
if (frame.CanGoBack)
{
frame.GoBack();
e.Handled = true;
}
}
Try the following code. It works for me.
private async void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
e.Handled = true;
var curpage = rootFrame.CurrentSourcePageType.FullName;
if(curpage=="your page name where you want to show dialog")
{
var msg = new MessageDialog("Sure to Exit?");
var okBtn = new UICommand("OK");
var cancelBtn = new UICommand("Cancel");
msg.Commands.Add(okBtn);
msg.Commands.Add(cancelBtn);
IUICommand result = await msg.ShowAsync();
if (result != null && result.Label == "OK")
{
Application.Current.Exit();
}
}
else
{
if (rootFrame.CanGoBack)
{
rootFrame.GoBack();
}
}
}
My understanding to your quesiton is everytime when user what to navigate back to the first page by pressing back button, you want to exit the app. If so, what we need to do is in the first page's OnNavigatedFrom event to check if the NavigationMode is Back. Try the following code:
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
if(e.NavigationMode == NavigationMode.Back)
{
App.Current.Exit();
}
}
If you want to delete the history of the first navigated page, you can remove it from BackStack, and the second page is considered as first one. Just put this on your mainpage:
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
Frame.BackStack.Remove(Frame.BackStack.First());
base.OnNavigatedFrom(e);
}