How to display a message in Windows Store Apps? - c#

How to display a message box in windows 8 apps using c# like calling MessageBox.Show() in windows phone 7?

MessageDialog msgDialog = new MessageDialog("Your message", "Your title");
//OK Button
UICommand okBtn = new UICommand("OK");
okBtn.Invoked = OkBtnClick;
msgDialog.Commands.Add(okBtn);
//Cancel Button
UICommand cancelBtn = new UICommand("Cancel");
cancelBtn.Invoked = CancelBtnClick;
msgDialog.Commands.Add(cancelBtn);
//Show message
msgDialog.ShowAsync();
And your call backs
private void CancelBtnClick(IUICommand command)
{
}
private void OkBtnClick(IUICommand command)
{
}
P.S. You can follow this tutorial for more.

The MessageDialog class should fit your needs.

My simpler way, for confirmation type message boxes:
var dlg = new MessageDialog("Are you sure?");
dlg.Commands.Add(new UICommand("Yes", null, "YES"));
dlg.Commands.Add(new UICommand("No", null, "NO"));
var op = await dlg.ShowAsync();
if ((string)op.Id == "YES")
{
//Do something
}

For simpler way, Just to display the message text and OK button. Use Windows.UI.Popups namespace. Create a method messagebox() that method should be
using Windows.UI.Popups;
protected async void messageBox(string msg)
{
var msgDlg = new Windows.UI.Popups.MessageDialog(msg);
msgDlg.DefaultCommandIndex = 1;
await msgDlg.ShowAsync();
}
Then call this method in your code like
messageBox("Unexpected error held");

Additional tidbit:
It appears in a modern Windows App a MessageDialog will not show prior to your app making its Window.Current.Active() call, which usually happens in the app class' OnLaunched() method. If you're trying to use MessageDialog to display something like a start-up exception, that's important to keep in mind.
My testing indicates MessageDialog.ShowAsync() may actually await but without the dialog being shown if Window.Current.Active() hasn't been called yet, so from a code execution standpoint it'll look like everything is working but yet no dialog is displayed.
If the goal is to display an exception during start-up, I can think of two options (there may be more).
Capture the exception information and then wait to display it until after Window.Current.Activate(). This can work if the exception is such that the application can recover from it and continue with start-up. For example, if there is an error restoring saved state information the app might want to report that to the user but then continue to start-up as if there was no saved state.
If the situation is such that the app is throwing up its hands and intending to terminate, but wants to let the user know what happened, then another solution might be to have a separate dedicated code block/method that plugs a new clean frame into Windows.Current.Content, activates it using Windows.Current.Activate(), and then invokes MessageDialog.ShowAsync(). I haven't experimented with this approach so I'm not sure if other conditions also need to be met like possibly loading a page into the frame.

use for page like:
private async void AppBarButton_Click(object sender, RoutedEventArgs e)
{
Windows.UI.Popups.MessageDialog a = new Windows.UI.Popups.MessageDialog("hello this is awth");
await a.ShowAsync();
}

Related

How to suppress push toast notification only when App in foreground?

Note: I have only tested this using the emulator, and pushing toasts using the built in functionality. I am assuming this isn't an emulator issue.
I followed this guide in order to intercept push toast notifications while the app is running. However, I only want to suppress the toast notification when the app is in the foreground. It should still display when another app is in the foreground. So I wrote the following handler in App.xaml.cs (and subscribed to the PushNotificationReceived event):
private async void OnPushNotification(PushNotificationChannel sender, PushNotificationReceivedEventArgs e)
{
string msg = "";
if (e.NotificationType == PushNotificationType.Toast)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
if (Window.Current.Visible)
{
msg += " Toast canceled.";
e.ToastNotification.SuppressPopup = true;
}
});
if (true) // actually determines if it's a certain type of toast
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
ConfirmationContentDialog confirmationDialog = new ConfirmationContentDialog();
confirmationDialog.SetMessage("Please confirm that you like turtles." + msg);
await confirmationDialog.ShowAsync();
});
}
}
}
So this works, in the sense that I only see the "toast canceled" message when the app was in the foreground when receiving the push notification. When I'm on the start screen or somewhere else I always get the toast. This is good. However, when the app is in the foreground, sometimes (usually after sending the second push) the toast shows up anyway (even though "Toast canceled" displays). But sometimes it doesn't. It's rather inconsistent.
This is leading me to believe that due to the await, sometimes the toast gets through before the code gets run on the UI thread to check whether the app is visible or not. However, I can't access Window.Current.Visible from here without using the dispatcher. I even tried CoreApplication.MainView.CoreWindow.Visible but that gives me "interface marshalled for different thread etc" exception. Speaking of which, I don't understand how CoreApplication.MainView.CoreWindow.Dispatcher can be called from anywhere but CoreApplication.MainView.CoreWindow.Visible not? How does that even work.
Anyway, how do I fix this? I would like to keep this within App.xaml.cs because I have a number of pages in this app, but this content dialog needs to be shown no matter which page the user is on, and without the user being redirected to a different page. However, I am of course open for new suggestions.
I fixed this as per Kai Brummund's suggestion by using a simple boolean toggle in the App class, and subscribing to the VisibilityChanged event like so:
private bool APP_VISIBLE = true;
protected override async void OnLaunched(LaunchActivatedEventArgs e)
{
// Stuff put here by Visual Studio
Window.Current.VisibilityChanged += OnVisibilityChanged;
Window.Current.Activate();
}
private void OnVisibilityChanged(object sender, VisibilityChangedEventArgs e)
{
if (e.Visible)
APP_VISIBLE = true;
else
APP_VISIBLE = false;
}
That way I can use APP_VISIBLE to suppress the popup without having to use the dispatcher and the toast is suppressed immediately.

WP8 custom message box crash

I have made a custom messagebox (discussed here) that shows localized quit prompt.
protected override void OnBackKeyPress(CancelEventArgs e)
{
//some conditions
e.Cancel = true;
string quitText = DeviceWrapper.Localize("QUIT_TEXT");
string quitCaption = DeviceWrapper.Localize("QUIT_CAPTION");
string quitOk = DeviceWrapper.Localize("DISMISS");
string quitCancel = DeviceWrapper.Localize("MESSAGEBOX_CANCEL");
IAsyncResult asyncResult = Guide.BeginShowMessageBox(
quitCaption, quitText, new List<string> { quitOk, quitCancel },
0, MessageBoxIcon.Error, null, null);
asyncResult.AsyncWaitHandle.WaitOne();
int? result = Guide.EndShowMessageBox(asyncResult);
if (result.HasValue && result.Value == 0)
e.Cancel = false;
//some more features
}
It works fine, but it does crash when it's run as stand-alone (without Visual Studio) after few seconds if user doesn't press anything.
I tried reproducing the same crash with phone attached using Release and Debug from Visual Studion, but it's as stable as it can possibly be. It only crashes when app is run from the phone itself.
How do I find the issue? What could be the reason for it? As far as I can tell, I cannot access crash logs on the device.
There should be something with the messagebox logic perhaps?
UPD
Few notes on your suggestion, Neil:
first of all VS warns me "the async method lacks await" stuff.
secondly I am not sure how to return info to "BackKeyPressed" that e.Cancel should equal "false". This should be the safe way to quit an app AFAIK.
And wouldn't we quit the "OnBackKeyPress" method if we run async method from it? That would mean that we can't let it know about our decision (e.Cancel = false).
Or if we don't quit the "OnBackKeyPress" then it could mean this event will stay for too long and the whole purpose is lost - app will be killed, right?
UPD2:
It seems that I am between Scylla and Charybdis: either I show a messagebox and experience crashes in runtime which is discouraged by guidelines, or I don't show a messagebox at all.
I've tried both native MessageBox and my implementation of custom messagebox with localized "Ok" and "Cancel" buttons. They behave the same: either they are synchronous and hang OnBackKeyPress, or they are async and OnBackKeyPress exits before we can let it know about user's decision.
Final decision
Apparently the guidelines state that we shouldn't ask user's confirmation at all.
Since there is no viable way to implement a working quit confirmation messagebox without crashing I've decided to not show it at all.
If you block or delay certain page events for too long, the OS will kill your app as it assumes its crashed...
OnNavigatedTo
OnNavigatedFrom
OnBackKeyPress
In your case, I would recommend putting the custom MessageBox in it's own method, then calling it on the UI thread.
private void customMessageBox()
{
// custom message box code
// use NavigationService.GoBack() if you need to exit
}
protected override void OnBackKeyPress(CancelEventArgs e)
{
e.Cancel = true;
Deployment.Current.Dispatcher.BeginInvoke(() => customMessageBox() );
}
I also found another answer which accomplishes the thing by making the method Async.
Debugger attached (or not)
When the Visual Studio debugger is attached, the OS does not warn you of certain errors such as high memory usage, page init delays, etc - so it is very important to test your app without the Visual Studio debugger attached either on device or in the emulator (Debug or Release)
Windows Phone 8.1
Be aware that the handling of the Back button has changed in WP8.1 XAML/WinRT apps. It might be something to consider if you're upgrading the app project in future.
I implemented this in my project and it worked. Try it!
protected override void OnBackKeyPress(CancelEventArgs e)
{
base.OnBackKeyPress(e);
e.Cancel = true;
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBoxResult result = MessageBox.Show("Hello", "Msg Box", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
//Do something
}
else
{
//Do something
}
});
}

Windows Phone - Store Universal App MessageDialog on launch

I want to show messagedialog when app starts. But in Universal app this code won't work.
I want to ask user for review.
Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
var composite = localSettings.Values["askforreview"];
if (composite == null)
{
localSettings.Values.Add("askforreview", true);
composite = true;
}
bool askforreview = Convert.ToBoolean(composite);
if (askforreview)
{
MessageDialog dialog = new MessageDialog("some message");
dialog .Commands.Add(new UICommand("Yes", ( command) =>
{
Launcher.LaunchUriAsync(CurrentApp.LinkUri);
}));
dialog.Commands.Add(new UICommand("Not Now"));
await dialog .ShowAsync();
}
When I debug app, I always get an error "a.ShowAsnyc" statement. Program stops in App.g.i.cs's this statement.
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
This type of exception (UnauthorizedAccessException - Access Denied) when it comes to MessageDialogs usually happens when you already have one MessageDialog opened when you try to open another one.
I was able to get your code to work on my side in both page constructor (without the await, though), and in page loaded async event handler. But if I tried to do it in two places one after another, it would throw an exception, for the reason mentioned above.
So, please check that you don't have another MessageDialog opened when you try to show this one. Did you perhaps leave this code in both the page constructor and the app launched event handler? That might cause it.

How do I keep my form on top and prevent it from losing focus?

If I want to make frmLogin without lose focus when I click at anywhere in frmLockScreen.
These two form are use topmost = true and call form frmMainClient.
showDialog is not good answer for me because it block another threads, but I just need no lose focus.
I will explain why.
I'm using SCS Framework to build my internet cafe program
This is what server called
public void LockScreen()
{
var client = CurrentClient;
client.ClientProxy.LockScreen();
}
This is what client provide to server
public void LockScreen()
{
_main.clearAndLockScreen();
}
If I use showDialog, then when running it would stuck at ShowDialog() line and can't send response message back to the server because it not complete this function. Then, server will catch exeception that does't have response from client after timeout reached.
public void clearAndLockScreen()
{
startTimeTextBox.InvokeIfRequired(s => { s.ResetText(); });
costTextBox.InvokeIfRequired(s => { s.ResetText(); });
memberIdLabel.InvokeIfRequired(s=>{ s.ResetText();});
_currentElapsedTimeDisplay.InvokeIfRequired(s =>
{
timerManager.reset();
s.ResetText();
});
expDateTB.InvokeIfRequired(s => { s.ResetText(); });
remainTB.InvokeIfRequired(s => { s.ResetText(); });
lockScreen.InvokeIfRequired(s =>
{
lockScreen = new LockScreen(this);
lockScreen.Show();
});
loginForm.InvokeIfRequired(s =>
{
loginForm = new LoginForm(this);
loginForm.ShowDialog();
});
process.MoveNext(Command.Logout);
}
Any ideas?
If you want to create a form that doesn't lose focus no matter what, you are out of luck. Raymond Chen explains this as a Windows design decision - it would be impossible for two programs to set their own windows as the super-topmost, so Windows doesn't let one program try either. Now, if you are somehow modifying the built-in Windows login screen, you may have more luck, since the winlogon process has extra privileges and can indeed switch desktops, respond to Ctrl-Alt-Delete, etc.
You could try setting the owner of the frmLogin to frmLockScreen
frmLogin.Show(this);
frmLogin.BringToFront();
and then set the event for the frmLockScreen Activated to bring the frmLogin to the front?
private void frmLockScreen_Activated(object sender, EventArgs e)
{
frmLogin.BringToFront();
frmLogin.Focus();
}
This worked for me on an old VB Project from a few years ago, made sure the password box was always set above the form that was blocking input to the desktop, Which I guess is what you are trying to achieve.
Martyn

Cross-threading forms in C# with Mono

I'm creating an application that uses .Net and Mono, it uses cross-threaded forms as I was having bad response from the child windows.
I created a test program with 2 forms: the first (form1) has a single button (button1) and the second (form2) is blank, code snippet below.
void openForm()
{
Form2 form2 = new Form2();
form2.ShowDialog();
}
private void button1_Click(object sender, EventArgs e)
{
Thread x = new Thread(openForm);
x.IsBackground = true;
x.Start();
}
This works fine in .Net, but with Mono, the first window will not gain focus when you click it (standard .ShowDialog() behaviour) rather than .Show() behaviour as .Net uses.
When I use .Show(), on .Net and Mono the window just flashes then disappears. If I put a 'MessageBox.Show()' after 'form2.Show()' it will stay open until you click OK.
Am I missing something in that code or does Mono just not support that? (I'm using Mono 2.8.1)
Thanks in advance, Adrian
EDIT: I realised I forgot 'x.IsBackground = true;' in the code above so child windows will close with the main window.
It's almost never the right thing to do in a Windows app to have more than one thread talk to one window or multiple windows which share the same message pump.
And it's rarely necessary to have more than one message pump.
The right way to do this is either to manually marshal everything back from your worker threads to your Window, using the 'Invoke' method, or use something like BackgroundWorker, which hides the details for you.
In summary:
Don't block the UI thread for time-consuming computation or I/O
Don't talk to the UI from more than one thread.
If you use Winforms controls, you shold "touch" the object always in main UI thread.
And at least - calling new Form.ShowDialog() in new thread does not make sense.
EDIT:
If you want easy work with Invoke/BeginInvoke you can use extension methods:
public static class ThreadingExtensions {
public static void SyncWithUI(this Control ctl, Action action) {
ctl.Invoke(action);
}
}
// usage:
void DoSomething( Form2 frm ) {
frm.SyncWithUI(()=>frm.Text = "Loading records ...");
// some time-consuming method
var records = GetDatabaseRecords();
frm.SyncWithUI(()=> {
foreach(var record in records) {
frm.AddRecord(record);
}
});
frm.SyncWithUI(()=>frm.Text = "Loading files ...");
// some other time-consuming method
var files = GetSomeFiles();
frm.SyncWithUI(()=>{
foreach(var file in files) {
frm.AddFile(file);
}
});
frm.SyncWithUI(()=>frm.Text = "Loading is complete.");
}

Categories

Resources