【问题标题】:How to open a specific URL (a YouTube video) on a button click in UWP C#?如何在 UWP C# 中单击按钮打开特定 URL(YouTube 视频)?
【发布时间】:2021-04-07 18:56:33
【问题描述】:

编辑: 我只是检查整个标签是否为空白,而不是标签中的 URL,因此它导致始终为空白并始终抛出异常。

我希望能够在用户的默认浏览器中通过单击按钮打开特定 URL,例如 YouTube 视频、谷歌搜索等

使用await Windows.System.Launcher.LaunchUriAsync(new Uri(url)); 时,URL 无效,此方法仅打开“普通”网站,例如https://microsoft.com

有什么方法可以在点击按钮时打开特定的 URL?

代码:

private async void imageTapEvent(object sender, RoutedEventArgs e)
    {
        try
        {
            if (((String)(((Image)sender).Tag)) != "")
                await Windows.System.Launcher.LaunchUriAsync(new Uri(((ImageTag)(((Image)sender).Tag)).url));
        }
        catch (Exception)
        {
            MessageDialog msg = new MessageDialog("The chosen URL is invalid", "Invalid URL");
            await msg.ShowAsync();
    }

标记是保存为字符串的 URL。

【问题讨论】:

    标签: c# url uwp uri


    【解决方案1】:

    有没有办法在 UWP 应用中打开特定的 URL?

    当然,UWP 有 WebView 控件用于渲染 html 页面,你可以给它 uri 源,然后 WebView 将在应用程序中渲染网站。更多详情请参考网页查看document

    <WebView x:Name="webView1" Source="http://www.contoso.com"/>
    

    更新

    您也可以启动默认浏览器来加载 uri,如下所示

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        string uriToLaunch = @"https://www.test.com";
        var uri = new Uri(uriToLaunch);
    
        // Set the option to show a warning
        var options = new Windows.System.LauncherOptions();
        options.TreatAsUntrusted = true;
    
        // Launch the URI with a warning prompt
        var success = await Windows.System.Launcher.LaunchUriAsync(uri, options);
    
        if (success)
        {
            // URI launched
        }
        else
        {
            // URI launch failed
        }
    
    }
    

    【讨论】:

    • 但就像我说的那样,我想在按钮单击事件上在默认浏览器中打开 URL。这可能吗?
    • 当然,您可以通过调用LaunchUriAsync 方法在浏览器中启动uri。
    • 但是只能用uri打开,就像用浏览器访问uri一样。
    • 我遇到了一个问题,因为在尝试启动 YouTube 视频时,会引发异常。它只打开网站,如 microsoft.com,而不是整个 YouTube 视频,就像我在问题中所说的那样。有什么解决方案还是我做错了什么?
    • 请在案例描述中分享您的代码。
    猜你喜欢
    • 2015-09-13
    • 1970-01-01
    • 1970-01-01
    • 2015-10-21
    • 2012-02-10
    • 2011-12-08
    • 2012-07-23
    • 2016-07-26
    • 2021-11-03
    相关资源
    最近更新 更多