dotnet / dotnet/wpf

Clipboard.SetText fails with CLIPBRD_E_CANT_OPEN

Open
#9,901 20 comments 2 reactions 0 assignees View on GitHub
Investigate
Dominant language
C#
Stars
7.7k
Forks
1.3k
Avg merge
1d 11h
Merged PRs (30d)
61

Description

### Description

Most of the time, the call to `Clipboard.SetText` takes several hundred milliseconds and then fails with CLIPBRD_E_CANT_OPEN in the flush operation.

The WinForms implementation works fine. Why is that? What is special about the WPF implementation? What is this "flushing" concept anyway? In Win32 API, there is no flushing. You just allocate a buffer and handover its ownership by calling `SetClipboardData`.

### Reproduction Steps

Attempt to copy text to clipboard in a WPF app like this:
```csharp
Clipboard.SetText("text");
```

### Expected behavior

It should place the text in clipboard immediately.

### Actual behavior

Most of the time, it takes several hundred milliseconds and then fails with the following exception:
```
System.Runtime.InteropServices.COMException (0x800401D0): Module OpenClipboard failed (0x800401D0 (CLIPBRD_E_CANT_OPEN))
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode, IntPtr errorInfo)
at System.Windows.Clipboard.Flush()
at WpfCopyTest.MainWindow.CopyButton_OnClick(Object sender, RoutedEventArgs e) in D:\Documents\WpfCopyTest\MainWindow.xaml.cs:line 39
```

### Regression?

_No response_

### Known Workarounds

The same code using `System.Windows.Forms.Clipboard` instead of `System.Windows.Clipboard` works without a problem.

### Impact

_No response_

### Configuration

.NET 8.0.400, Windows 11 23H2, x64

I don't think I have anything unusual installed that would monitor the clipboard and block it.
I tried disabling Windows clipboard history with no effect.

### Other information

It doesn't look like a widespread issue, perhaps it's configuration specific.

Possibly related to #9106.

The reason I'm involved is that I'm trying to fix the clipboard issue in PowerToys: https://github.com/microsoft/PowerToys/issues/25437

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.