Skip to content

Clipboard.SetContent Throwing COMException #10968

@nlogozzo

Description

@nlogozzo

Describe the bug

When calling Clipboard.SetContent(package) I am getting the following error AND THE TEXT IS NOT COPIED TO CLIPBOARD:

System.Runtime.InteropServices.COMException: 'CoInitialize has not been called. (0x800401F0 (CO_E_NOTINITIALIZED))'
System.Runtime.InteropServices.COMException
  HResult=0x800401F0
  Message=CoInitialize has not been called. (0x800401F0 (CO_E_NOTINITIALIZED))
  Source=WinRT.Runtime
  StackTrace:
   at WinRT.ExceptionHelpers.<ThrowExceptionForHR>g__Throw|20_0(Int32 hr)
   at ABI.Windows.ApplicationModel.DataTransfer.IClipboardStaticsMethods.SetContent(IObjectReference _obj, DataPackage content)
   at Windows.ApplicationModel.DataTransfer.Clipboard.SetContent(DataPackage content)
   at NickvisionTubeConverter.WinUI.Controls.DownloadRow.<ViewLog>d__28.MoveNext() in C:\Users\nlogo\OneDrive\Documents\Programming\Parabolic\NickvisionTubeConverter.WinUI\Controls\DownloadRow.xaml.cs:line 216

Steps to reproduce the bug

Here is my code:

private async void ViewLog(object sender, RoutedEventArgs e)
{
    var logDialog = new ContentDialog()
    {
        Title = _("Log"),
        Content = new ScrollViewer()
        {
            MaxHeight = 200,
            Content = new TextBlock()
            {
                Margin = new Thickness(0, 0, 14, 0),
                Text = _log,
                TextWrapping = TextWrapping.WrapWholeWords
            }
        },
        PrimaryButtonText = _("Copy to Clipboard"),
        CloseButtonText = _("OK"),
        DefaultButton = ContentDialogButton.Close,
        XamlRoot = _xamlRoot
    };
    var res = await logDialog.ShowAsync();
    if(res == ContentDialogResult.Primary)
    {
        var package = new DataPackage();
        package.SetText(_log);
        Clipboard.SetContent(package);
    }
}

It basically shows the _log variable in a ContentDialog with an option to copy it to the clipboard. Upon hitting the line Clipboard.SetContent(package) is when the error is thrown.

Expected behavior

The text is copied to the clipboard without any error thrown.

Screenshots

No response

NuGet package version

Windows App SDK 1.4.2: 1.4.231008000

Packaging type

Unpackaged

Windows version

Windows 11 version 22H2 (22621, 2022 Update)

IDE

Visual Studio 2022

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs-triageIssue needs to be triaged by the area owners

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions