Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added WinAppSDK background task sample #366

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.10.35013.160
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WinMainCOMBGTaskSample", "WinMainCOMBGTaskSample\WinMainCOMBGTaskSample.vcxproj", "{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM64 = Debug|ARM64
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|ARM64 = Release|ARM64
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Debug|ARM64.ActiveCfg = Debug|ARM64
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Debug|ARM64.Build.0 = Debug|ARM64
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Debug|ARM64.Deploy.0 = Debug|ARM64
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Debug|x64.ActiveCfg = Debug|x64
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Debug|x64.Build.0 = Debug|x64
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Debug|x64.Deploy.0 = Debug|x64
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Debug|x86.ActiveCfg = Debug|Win32
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Debug|x86.Build.0 = Debug|Win32
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Debug|x86.Deploy.0 = Debug|Win32
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Release|ARM64.ActiveCfg = Release|ARM64
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Release|ARM64.Build.0 = Release|ARM64
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Release|ARM64.Deploy.0 = Release|ARM64
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Release|x64.ActiveCfg = Release|x64
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Release|x64.Build.0 = Release|x64
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Release|x64.Deploy.0 = Release|x64
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Release|x86.ActiveCfg = Release|Win32
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Release|x86.Build.0 = Release|Win32
{B1C0CFB3-FD1F-4249-81A1-CDA96129F325}.Release|x86.Deploy.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4F22EA65-ABA7-4D96-ACC3-25A7A023CC21}
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<Application
x:Class="WinMainCOMBGTaskSample.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WinMainCOMBGTaskSample">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<XamlControlsResources xmlns="using:Microsoft.UI.Xaml.Controls" />
<!-- Other merged dictionaries here -->
</ResourceDictionary.MergedDictionaries>
<!-- Other app resources here -->
</ResourceDictionary>
</Application.Resources>
</Application>
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
#include "pch.h"
#include "App.xaml.h"
#include "MainWindow.xaml.h"
#include "RegisterForCom.h"
#include "Win32BGClass.h"

using namespace winrt;
using namespace Microsoft::UI::Xaml;
using namespace winrt::WinMainCOMBGTaskSample;

// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.

namespace winrt::WinMainCOMBGTaskSample::implementation
{
/// <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>
App::App()
{
// Xaml objects should not call InitializeComponent during construction.
// See https://github.com/microsoft/cppwinrt/tree/master/nuget#initializecomponent

#if defined _DEBUG && !defined DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException([](IInspectable const&, UnhandledExceptionEventArgs const& e)
{
if (IsDebuggerPresent())
{
auto errorMessage = e.Message();
__debugbreak();
}
});
#endif
}

/// <summary>
/// Invoked when the application is launched.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
void App::OnLaunched([[maybe_unused]] LaunchActivatedEventArgs const& e)
{
window = make<MainWindow>();
window.Activate();
}

}

int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nShowCmd)
{
winrt::init_apartment(winrt::apartment_type::single_threaded);
OutputDebugString(L"This is command line args: ");
OutputDebugString(lpCmdLine);

if (std::wcsncmp(lpCmdLine, RegisterForCom::RegisterForComToken, sizeof(RegisterForCom::RegisterForComToken)) == 0)
{
RegisterForCom comRegister;
comRegister.RegisterAndWait(__uuidof(Win32BGTask));
MSG msg;

while (-1 != GetMessage(&msg, NULL, 0, 0) &&
WM_QUIT != msg.message)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
else
{
// put your fancy code somewhere here
::winrt::Microsoft::UI::Xaml::Application::Start(
[](auto&&)
{
::winrt::make<::winrt::WinMainCOMBGTaskSample::implementation::App>();
});
}

return 0;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#pragma once

#include "App.xaml.g.h"

namespace winrt::WinMainCOMBGTaskSample::implementation
{
struct App : AppT<App>
{
App();

void OnLaunched(Microsoft::UI::Xaml::LaunchActivatedEventArgs const&);

private:
winrt::Microsoft::UI::Xaml::Window window{ nullptr };
};
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
namespace WinMainCOMBGTaskSample
{
[default_interface]
runtimeclass MainWindow : Microsoft.UI.Xaml.Window
{
MainWindow();
Int32 MyProperty;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<Window
x:Class="WinMainCOMBGTaskSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WinMainCOMBGTaskSample"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button x:Name="myButton" Click="myButton_Click">Click Me</Button>
</StackPanel>
</Window>
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
#include "pch.h"
#include "MainWindow.xaml.h"
#if __has_include("MainWindow.g.cpp")
#include "MainWindow.g.cpp"
#endif
#include "Win32BGClass.h"
#include "ToastNotificationCreator.h"

using namespace winrt;
using namespace Microsoft::UI::Xaml;
namespace winrt
{
using namespace winrt::Windows::ApplicationModel::Background;
}

// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.

namespace winrt::WinMainCOMBGTaskSample::implementation
{
int32_t MainWindow::MyProperty()
{
throw hresult_not_implemented();
}

void MainWindow::MyProperty(int32_t /* value */)
{
throw hresult_not_implemented();
}

void MainWindow::myButton_Click(IInspectable const&, RoutedEventArgs const&)
{
myButton().Content(box_value(L"BG Task Registered, Delete Toast Notification to trigger BG Task"));
RegisterTask(winrt::ToastNotificationHistoryChangedTrigger(), L"Win32BGTask", __uuidof(Win32BGTask), true);
ToastNotificationCreator();
}


void MainWindow::UnregisterDuplicateTask(_In_ hstring taskName)
{
auto allRegistrations = BackgroundTaskRegistration::AllTasks();
for (auto taskPair : allRegistrations)
{
IBackgroundTaskRegistration task = taskPair.Value();
if (taskName == task.Name())
{
task.Unregister(true);
}
}
}

hresult MainWindow::RegisterTask(_In_ IBackgroundTrigger trigger, _In_ hstring taskName, _In_ guid classId, _In_ bool UnregisterOldTask)
{
hresult hr;

try
{
if (UnregisterOldTask)
{
UnregisterDuplicateTask(taskName);
}

BackgroundTaskBuilder taskBuilder;
taskBuilder.SetTrigger(trigger);
taskBuilder.Name(taskName);
taskBuilder.SetTaskEntryPointClsid(classId);

taskBuilder.Register();
}
catch (...)
{
hr = to_hresult();
}

return hr;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#pragma once

#include "MainWindow.g.h"

namespace winrt::WinMainCOMBGTaskSample::implementation
{
struct MainWindow : MainWindowT<MainWindow>
{
MainWindow()
{
// Xaml objects should not call InitializeComponent during construction.
// See https://github.com/microsoft/cppwinrt/tree/master/nuget#initializecomponent
}

int32_t MyProperty();
void MyProperty(int32_t value);
void MainWindow::UnregisterDuplicateTask(_In_ winrt::hstring taskName);
winrt::hresult MainWindow::RegisterTask(_In_ winrt::Windows::ApplicationModel::Background::IBackgroundTrigger trigger, _In_ hstring taskName, _In_ guid classId, _In_ bool UnregisterOldTask = false);
void myButton_Click(IInspectable const& sender, Microsoft::UI::Xaml::RoutedEventArgs const& args);
};
}

namespace winrt::WinMainCOMBGTaskSample::factory_implementation
{
struct MainWindow : MainWindowT<MainWindow, implementation::MainWindow>
{
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
<?xml version="1.0" encoding="utf-8"?>

<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
xmlns:com="http://schemas.microsoft.com/appx/manifest/com/windows10"
IgnorableNamespaces="uap rescap">

<Identity
Name="55876930-62ad-4023-abd3-563579acd97b"
Publisher="CN=godlyalias"
Version="1.0.0.0" />

<mp:PhoneIdentity PhoneProductId="55876930-62ad-4023-abd3-563579acd97b" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>

<Properties>
<DisplayName>WinMainCOMBGTaskSample</DisplayName>
<PublisherDisplayName>godlyalias</PublisherDisplayName>
<Logo>Assets\StoreLogo.png</Logo>
</Properties>

<Dependencies>
<TargetDeviceFamily Name="Windows.Desktop" MinVersion="10.0.22000.0" MaxVersionTested="10.0.26000.0" />
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.22000.0" MaxVersionTested="10.0.26000.0" />
</Dependencies>

<Resources>
<Resource Language="x-generate"/>
</Resources>

<Applications>
<Application Id="App"
Executable="$targetnametoken$.exe"
EntryPoint="$targetentrypoint$">
<uap:VisualElements
DisplayName="WinMainCOMBGTaskSample"
Description="WinMainCOMBGTaskSample"
BackgroundColor="transparent"
Square150x150Logo="Assets\Square150x150Logo.png"
Square44x44Logo="Assets\Square44x44Logo.png">
<uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png" />
<uap:SplashScreen Image="Assets\SplashScreen.png" />
</uap:VisualElements>

<Extensions>
<com:Extension Category="windows.comServer">
<com:ComServer>
<com:ExeServer Executable="WinMainCOMBGTaskSample.exe" Arguments="-RegisterForBGTaskServer" DisplayName="WinMainCOMBGTaskSample">
<com:Class Id="12345678-1234-1234-1234-1234567890AB" DisplayName="WinMainCOMBGTaskSample Win32BGTask" />
</com:ExeServer>
</com:ComServer>
</com:Extension>
</Extensions>
</Application>
</Applications>


<Capabilities>
<Capability Name="internetClient" />
<rescap:Capability Name="runFullTrust" />
</Capabilities>
</Package>
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
---
page_type: sample
languages:
- cpp
products:
- windows
- windows-api-win32
- windows-app-sdk
name: WinMainCOMBGTaskSample sample
urlFragment: WinMainCOMBGTaskSample
description: Demonstrates how to use register background task in a win32 application.
extendedZipContent:
- path: LICENSE
- target: LICENSE
---

# WinMainCOMBGTaskSample sample

This sample application demonstrates how a **WinUI3** app can register Background Task. In this sample usage of ToastNotificationHistoryChangedTrigger is demonstrated which can be easily changed to any supported triggers. On clicking the button on the UI, background task gets registered and a toast notification will get pushed, when user deletes this toast notification background task gets triggered and push another toast notification to notify that BackgroundTask have been triggered.

## Prerequisites

* See [System requirements for Windows app development](https://docs.microsoft.com/windows/apps/windows-app-sdk/system-requirements).
* Make sure that your development environment is set up correctly&mdash;see [Install tools for developing apps for Windows 10 and Windows 11](https://docs.microsoft.com/windows/apps/windows-app-sdk/set-up-your-development-environment).


## Building and running the sample

* Open the solution file (`.sln`) in Visual Studio.
* Press Ctrl+Shift+B, or select **Build** \> **Build Solution**.

## Related Links

- [Windows App SDK](https://docs.microsoft.com/windows/apps/windows-app-sdk/)
Loading