I am wanting my app to launch when the user logs into Windows. Currently, I can do this by opening up Task Manager > Startup > and setting 'Enable' for my app. I am wanting to do this within my app though, and have followed this guide. However, when requesting the app to run at startup, it always throws the exception below:
The group or resource is not in the correct state to perform the requested operation.
This doesn't make sense to me, as my app only calls RequestEnableAsync()
if the StartupTaskState
is Disabled
, as seen in my code below:
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;
}
And the full error output:
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()
The code above is called via a DependencyService
, when a button is clicked.
I was able to solve this simply by running the code on the main thread. IE, wrapping it inside of Device.BeginInvokeOnMainThread(async () => { ... });
User contributions licensed under CC BY-SA 3.0