Winui 3 - Clipboard API not working.

Peter DC 21 Reputation points
2022-03-21T15:26:13.077+00:00

The following

var dataPackage = new DataPackage();

dataPackage.SetText(texttocopy);

Clipboard.SetContent(dataPackage);

which works in UWP fails with the following error message -

CoInitialize has not been called.

Paste does also not work.

I cannot find anything in the documentation or samples relating to the clipboard.

Windows App SDK
Windows App SDK
A set of Microsoft open-source libraries, frameworks, components, and tools to be used in apps to access Windows platform functionality on many versions of Windows. Previously known as Project Reunion.
731 questions
{count} votes

Accepted answer
  1. tmk907 81 Reputation points
    2022-04-02T15:45:41.33+00:00

    This error is caused by async Main method, it doesn't work in C# WinUI apps.
    Here you can find sample that doesn't use async Main WindowsAppSDK-Samples

    Replace
    await keyInstance.RedirectActivationToAsync(args);
    with
    RedirectActivationTo(args, keyInstance);

    and add following code to Program.cs

    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]

    private static extern IntPtr CreateEvent(
    IntPtr lpEventAttributes, bool bManualReset,
    bool bInitialState, string lpName);

    [DllImport("kernel32.dll")]
    private static extern bool SetEvent(IntPtr hEvent);

    [DllImport("ole32.dll")]
    private static extern uint CoWaitForMultipleObjects(
    uint dwFlags, uint dwMilliseconds, ulong nHandles,
    IntPtr[] pHandles, out uint dwIndex);

    private static IntPtr redirectEventHandle = IntPtr.Zero;

    // Do the redirection on another thread, and use a non-blocking
    // wait method to wait for the redirection to complete.
    public static void RedirectActivationTo(AppActivationArguments args, AppInstance keyInstance)
    {
    redirectEventHandle = CreateEvent(IntPtr.Zero, true, false, null);
    Task.Run(() =>
    {
    keyInstance.RedirectActivationToAsync(args).AsTask().Wait();
    SetEvent(redirectEventHandle);
    });
    uint CWMO_DEFAULT = 0;
    uint INFINITE = 0xFFFFFFFF;
    _ = CoWaitForMultipleObjects(
    CWMO_DEFAULT, INFINITE, 1,
    new IntPtr[] { redirectEventHandle }, out uint handleIndex);
    }

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Castorix31 82,116 Reputation points
    2022-03-21T15:50:56.473+00:00

    It works fine for me with Windows App SDK 1.0.1 on Windows 10 21H1
    Test with a Clipboard Viewer with "dataPackage.SetText("Test Clipboard");" :

    185303-testclipboard.gif