Skip to main content
 首页 » 编程设计

c#之在 Windows 应用商店应用程序中显示来自 app.xaml.cs 的 MessageDialog

2024年02月05日36think

我试图在失去互联网连接时向用户显示一条消息

我的 App.xaml.cs 上有这个方法

static async void NetworkInformation_NetworkStatusChanged(object sender) 
    { 
 
        //Get the Internet connection profile 
        //ConnectionProfile connectionProfileInfo = null; 
        try 
        { 
            ConnectionProfile InternetConnectionProfile = NetworkInformation.GetInternetConnectionProfile(); 
 
            if (InternetConnectionProfile == null) 
            { 
                ApplicationData.Current.LocalSettings.Values["INTERNET"] = false; 
 
                ShowBox("Internet Lost"); 
 
                Frame rootFrame = Window.Current.Content as Frame; 
                rootFrame.Navigate(typeof(LoginPage)); 
            } 
            else 
            { 
                ApplicationData.Current.LocalSettings.Values["INTERNET"] = true; 
            } 
        } 
        catch (Exception ex) 
        { 
            Debug.WriteLine("Unexpected exception occurred: " + ex.ToString()); 
        } 
 
    } 

还有这个

public async static void ShowBox(string msg) 
    { 
        try 
        { 
 
            await new MessageDialog(msg, "No Internet").ShowAsync(); 
        } 
        catch (Exception e) 
        { 
            Debug.WriteLine(e.Message); 
        } 
    } 

当我导致连接丢失(禁用我的互联网连接)时,ShowBox 方法被调用,我得到了这个异常:

Invalid window handle.

必须从具有 CoreWindow 或窗口的线程调用此 API 必须明确设置。

有什么方法可以显示该事件的 MessageDialog 吗?

请您参考如下方法:

尝试添加这个:

CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, 
() => 
{ 
    MessageDialog msg= new MessageDialog("No Internet"); 
    msg.ShowAsync(); 
 });