Xamarin.Forms UWP - 请求启用应用程序在启动时运行

时间:2018-05-17 07:41:55

标签: c# xamarin xamarin.forms uwp

我希望我的应用在用户登录Windows时启动。目前,我可以通过打开任务管理器>来完成此操作。启动>并为我的应用设置“启用”。我想在我的应用程序中执行此操作,并遵循this guide。但是,当请求应用程序在启动时运行时,它总是抛出以下异常:

The group or resource is not in the correct state to perform the requested operation.

这对我没有意义,因为如果RequestEnableAsync()StartupTaskState,我的应用只会调用Disabled,如下面的代码所示:

private async Task<bool> SetLaunchOnLogin_UWP_Async(bool shouldLaunchOnLogin)
{
    try
    {
        var startupTask = await StartupTask.GetAsync("MyProjectStartupId");

        switch (startupTask.State)
        {
            case StartupTaskState.Disabled:

                Debug.WriteLine("Startup is disabled. Will ask");
                // The code reaches here, but always throws an exception 
                // when calling RequestEnableAsync():
                var newState = await startupTask.RequestEnableAsync()
                return newState == StartupTaskState.Enabled;
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(
            "SpecificPlatformFunctions_UWP - SetLaunchOnLogin_UWP_Async ERROR: " 
            + ex.ToString());
    }

    return false;
}

完整的错误输出:

Startup is disabled. Will ask
Exception thrown: 'System.Exception' in System.Private.CoreLib.ni.dll
SpecificPlatformFunctions_UWP - SetLaunchOnLogin_UWP_Async ERROR: System.Exception: The group or resource is not in the correct state to perform the requested operation. (Exception from HRESULT: 0x8007139F)
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at MyProject.UWP.DependencyServices.SpecificPlatformFunctions_UWP.<SetLaunchOnLogin_UWP_Async>d__13.MoveNext()

单击按钮时,上面的代码通过DependencyService调用。

1 个答案:

答案 0 :(得分:2)

我能够通过在主线程上运行代码来解决这个问题。 IE,将其包装在from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import pyqtSlot from A3AMainWindow import Ui_MainWindow class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__() self.setupUi(self) self.connect(self.btn_inv_cancel.clicked.connect(self.on_click)) @pyqtSlot() def on_click(self): QMessageBox.Information(Self, "hello") if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())