分享后Windows 8 App启动

时间:2014-12-21 17:11:06

标签: c# .net windows-8 windows-applications charms-bar

我正在寻找通过魅力栏与其共享一些内容后启动我自己的Windows应用程序的可能性。 我找到了这个MS示例https://code.msdn.microsoft.com/windowsapps/Sharing-Content-Target-App-e2689782/ 但点击分享按钮后,应用程序将关闭。 我在按钮点击方法中试用了这段代码:

var rootFrame = new Frame();
rootFrame.Navigate(typeof(DefaultPage));
Window.Current.Content = rootFrame;
Window.Current.Activate();

但这没有效果。我也尝试使用Application.Start(),但参数应该是一个回调,我不明白哪一个。

-------编辑: 我想要以下行为。

  1. 打开IE(已经完成)
  2. 打开Charm Bar并单击“共享(已完成)
  3. 选择我的应用程序(已完成)
  4. 我的应用程序显示包含信息的共享页面和共享按钮(已完成)
  5. 点击我的应用程序的分享按钮后打开主页(在MS示例中为默认页面)
  6. 所以我找不到最后一步的解决方案。从我的应用程序的“共享”页面切换到我的应用程序的主页面。

    编辑结束-------

    我想要的每件事都是在与它共享一些内容后启动我的应用程序。 我希望有人可以帮助我。或者这不可能吗?

    ----编辑2:

    App.xaml.cs:

    using System;
    using Windows.ApplicationModel;
    using Windows.ApplicationModel.Activation;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Navigation;
    
        // The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227
    
        namespace AppName
        {
            /// <summary>
            /// Provides application-specific behavior to supplement the default Application class.
            /// </summary>
            sealed partial class App : Application
            {
                /// <summary>
                /// Initializes the singleton application object.  This is the first line of authored code
                /// executed, and as such is the logical equivalent of main() or WinMain().
                /// </summary>
                public App()
                {
                    this.InitializeComponent();
                    this.Suspending += OnSuspending;
                }
    
                /// <summary>
                /// Invoked when the application is launched normally by the end user.  Other entry points
                /// will be used such as when the application is launched to open a specific file.
                /// </summary>
                /// <param name="e">Details about the launch request and process.</param>
            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();
                    // Set the default language
                    rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
    
                    rootFrame.NavigationFailed += OnNavigationFailed;
    
                    if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                    {
                        //TODO: Load state from previously suspended application
                    }
    
                    // Place the frame in the current Window
                    Window.Current.Content = rootFrame;
                }
    
                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(MainPage), e.Arguments);
                }
                // Ensure the current window is active
                Window.Current.Activate();
            }
    
            /// <summary>
            /// Invoked when Navigation to a certain page fails
            /// </summary>
            /// <param name="sender">The Frame which failed navigation</param>
            /// <param name="e">Details about the navigation failure</param>
            void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
            {
                throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
            }
    
            /// <summary>
            /// Invoked when application execution is being suspended.  Application state is saved
            /// without knowing whether the application will be terminated or resumed with the contents
            /// of memory still intact.
            /// </summary>
            /// <param name="sender">The source of the suspend request.</param>
            /// <param name="e">Details about the suspend request.</param>
            private void OnSuspending(object sender, SuspendingEventArgs e)
            {
                var deferral = e.SuspendingOperation.GetDeferral();
                //TODO: Save application state and stop any background activity
                deferral.Complete();
            }
    
            /// <summary>
            /// Invoked when the application is activated as the target of a sharing operation.
            /// </summary>
            /// <param name="e">Details about the activation request.</param>
            protected override void OnShareTargetActivated(Windows.ApplicationModel.Activation.ShareTargetActivatedEventArgs e)
            {
                var shareTargetPage = new AppName.ShareTargetPage();
                shareTargetPage.Activate(e);
                Window.Current.Activate();
            }
    
            protected override void OnActivated(IActivatedEventArgs args)
            {
                base.OnActivated(args);
            }
    
        }
    }
    

    MainPage.xaml.cs中:

    using System;
    using Windows.UI.Xaml.Controls;
    
    
    // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
    
    namespace AppName
    {
        /// <summary>
        /// An empty page that can be used on its own or navigated to within a Frame.
        /// </summary>
        public sealed partial class MainPage : Page
        {
            public MainPage()
            {
                this.InitializeComponent();
            }
    
            public void ReceiveUri(Uri sharedWebLink)
            {
                tbMessages.Text = sharedWebLink.ToString();
            }
    
            protected override void OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs e)
            {
                // It is possible to get in this method after the Share button at the 
                // sharetargetpage is clicked but at this point I don't know how to 
                // activate the app
    
                //base.OnNavigatedTo(e);
            }
    
        }
    }
    

    Sharepargetpage.xaml.cs:

    using Windows.UI.Core;
    using AppName.Common;
    using System;
    using Windows.ApplicationModel.Activation;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Media.Imaging;
    
    // The Share Target Contract item template is documented at http://go.microsoft.com/fwlink/?LinkId=234241
    
    namespace AppName
    {
        /// <summary>
        /// This page allows other applications to share content through this application.
        /// </summary>
        public sealed partial class ShareTargetPage : Page
        {
            private Uri sharedWebLink;
    
    
            /// <summary>
            /// Provides a channel to communicate with Windows about the sharing operation.
            /// </summary>
            private Windows.ApplicationModel.DataTransfer.ShareTarget.ShareOperation _shareOperation;
            private ObservableDictionary defaultViewModel = new ObservableDictionary();
    
            /// <summary>
            /// This can be changed to a strongly typed view model.
            /// </summary>
            public ObservableDictionary DefaultViewModel
            {
                get { return this.defaultViewModel; }
            }
    
            public ShareTargetPage()
            {
                this.InitializeComponent();
            }
    
            /// <summary>
            /// Invoked when another application wants to share content through this application.
            /// </summary>
            /// <param name="e">Activation data used to coordinate the process with Windows.</param>
            public async void Activate(ShareTargetActivatedEventArgs e)
            {
                this._shareOperation = e.ShareOperation;
    
                // Communicate metadata about the shared content through the view model
                var shareProperties = this._shareOperation.Data.Properties;
                var thumbnailImage = new BitmapImage();
                this.DefaultViewModel["Title"] = shareProperties.Title;
                this.DefaultViewModel["Description"] = shareProperties.Description;
                this.DefaultViewModel["Image"] = thumbnailImage;
                this.DefaultViewModel["Sharing"] = false;
                this.DefaultViewModel["ShowImage"] = false;
                this.DefaultViewModel["Comment"] = String.Empty;
                this.DefaultViewModel["Placeholder"] = "Add a comment";
                this.DefaultViewModel["SupportsComment"] = true;
                Window.Current.Content = this;
                Window.Current.Activate();
    
                try
                {
                    this.sharedWebLink = await this._shareOperation.Data.GetWebLinkAsync();
                    this.DefaultViewModel["URL"] = this.sharedWebLink.ToString();
                }
                catch (Exception ex)
                {
                    NotifyUserBackgroundThread("Failed GetWebLinkAsync - " + ex.Message, NotifyType.ErrorMessage);
                }
    
                // Update the shared content's thumbnail image in the background
                if (shareProperties.Thumbnail != null)
                {
                    var stream = await shareProperties.Thumbnail.OpenReadAsync();
                    thumbnailImage.SetSource(stream);
                    this.DefaultViewModel["ShowImage"] = true;
                }
            }
    
            /// <summary>
            /// Invoked when the user clicks the Share button.
            /// </summary>
            /// <param name="sender">Instance of Button used to initiate sharing.</param>
            /// <param name="e">Event data describing how the button was clicked.</param>
            private void ShareButton_Click(object sender, RoutedEventArgs e)
            {
                this.DefaultViewModel["Sharing"] = true;
                this._shareOperation.ReportStarted();
    
                // TODO: Perform work appropriate to your sharing scenario using
                //       this._shareOperation.Data, typically with additional information captured
                //       through custom user interface elements added to this page such as 
                //       this.DefaultViewModel["Comment"]
    
                this._shareOperation.ReportCompleted();
    
                // TRY1: Navigate to MainPage
                //Frame rootFrame = Window.Current.Content as Frame;
                //if(rootFrame == null)
                //{
                //    rootFrame = new Frame();
                //    Window.Current.Content = rootFrame;
                //}
                //if(rootFrame.Content == null)
                //{
                //    rootFrame.Navigate(typeof(MainPage));
                //}
    
                //  TRY2: Navigate to MainPage
                //var p = rootFrame.Content as MainPage;
                //p.ReceiveUri(sharedWebLink);
                //Window.Current.Activate();
    
    
                var rootFrame = new Frame();
                rootFrame.Navigate(typeof(MainPage));
                Window.Current.Content = rootFrame;
                Window.Current.Activate();
    
                // TRY3: Start the App
                // Application.Start();
                // App.Start();
                // but I don't know which callback method should be the param of start
            }
    
            async private void NotifyUserBackgroundThread(string message, NotifyType type)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    NotifyUser(message, type);
                });
            }
    
            private void NotifyUser(string strMessage, NotifyType type)
            {
                switch (type)
                {
                    // Use the status message style.
                    case NotifyType.StatusMessage:
                        StatusBlock.Style = Resources["StatusStyle"] as Style;
                        break;
                    // Use the error message style.
                    case NotifyType.ErrorMessage:
                        StatusBlock.Style = Resources["ErrorStyle"] as Style;
                        break;
                }
                StatusBlock.Text = strMessage;
            }
    
            public enum NotifyType
            {
                StatusMessage,
                ErrorMessage
            };
        }
    }
    

    编辑2结束---------

2 个答案:

答案 0 :(得分:0)

要将应用的行为设为“共享定位”应用,您必须覆盖OnShareTargetActivated(ShareTargetActivatedEventArgs args)课程中的App方法。

protected override void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
{
    var rootFrame = new Frame();

    // TODO: Load content in frame

    Window.Current.Content = rootFrame;
    Window.Current.Activate();
}

修改

从您当前的实现中,您将在窗口内设置ShareTargetPage,然后将Windows.Current.Content转换为始终为null的Frame。所以,你不能这样做。我的建议是这样做。

将App.xaml.cs中的OnShareTargetActivated方法更改为此

protected override void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
{
    var rootFrame = new Frame();
    rootFrame.Navigate(typeof(ShareTargetPage), args);
    Window.Current.Content = rootFrame;
    Window.Current.Activate();
}

从ShareTargetPage.xaml.cs

中的Activate方法中删除它
Window.Current.Content = this;
Window.Current.Activate();

覆盖OnNavigatedTo

中的ShareTargetPage
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    // Calling Activate method here
    Activate((ShareTargetActivatedEventArgs)e.Parameter);
}

然后要导航到另一个页面,您只需在Frame.Navigation

内调用ShareTargetPage之类的内容
this.Frame.Navigate(typeof(MainPage));

编辑2

如果要导航到共享按钮上的其他页面,请单击,然后删除此行代码

this._shareOperation.ReportCompleted();

此调用上述方法通知操作系统您的应用已完成共享请求,现在已安全终止。这就是为什么你的应用终止而不导航到另一个页面的原因

答案 1 :(得分:0)

您尝试执行的操作违反了Windows应用商店的指导原则,如果您成功实现了该应用,您的应用将被拒绝。

请参阅此处的指南:http://msdn.microsoft.com/en-us/library/windows/apps/hh465251.aspx

您的共享目标应用必须仅作为共享目标弹出,并且必须在共享面板之外的任何用户交互中解除。

您可以通过在共享面板中添加按钮“启动完整应用”来解决此问题,然后创建启动应用的自定义URI。但这可能是不可取的。