WPF 中 OpenClipboard 失败问题 - HRESULT: 0x800401D0 的解决方案

本文介绍了在WPF应用中遇到OpenClipboard失败,HRESULT为0x800401D0的两个解决方案。问题根源在于Clipboard.SetText()方法引发异常。方案一是在App.xaml中处理Application.DispatcherUnhandledException事件。方案二是使用Clipboard.SetDataObject()代替Clipboard.SetText()来设置剪贴板文本。对于DataGrid复制问题,DataGridTextColumn可直接复制,DataGridTemplateColumn需添加AllowDrop属性并实现拖放操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解决方案可以参照:https://stackoverflow.com/questions/12769264/openclipboard-failed-when-copy-pasting-data-from-wpf-datagrid

关键的问题在于 Clipboard.SetText() 方法会触发异常。

 

方案一:

It is a bug in the WPF Clipboard handler. You need to handle the unhandled exception in the Application.DispatcherUnhandledException event.

Add this attribute to the Application element in your App.xaml

DispatcherUnhandledException="Application_DispatcherUnhandledException"

 

Add this code to your App.xaml.cs file

void Application_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
    var comException = e.Exception as System.Runtime.InteropServices.COMException;

    if (comException != null && comException.ErrorCode == -2147221040)
         e.Handled = true;
}

 

方案二:

We are using .NET 4.0. We had the same problem, but after logging off the system, code used to work fine for some time.

Finally we found the alternative.

If you want to copy a string to the clipboard,

string data = "Copy This"

Till now I was using the following method

Clipboard.SetText(data);

It was failing again and again. Then I looked at other methods available to set text in the clipboard in Clipboard Class and tried the following:

Clipboard.SetDataObject(data);

And it worked :). I never had the issue again.

 

更多的方案参照最上方的链接。

 

如果是 DataGrid 的复制问题,一般 DataGridTextColumn 是可以直接进行复制的,如果是 DataGridTemplateColumn,则需要添加

ClipboardContentBinding="{Binding 属性}"

到 DataGridTemplateColumn 中就能解决此问题。

转载于:https://www.cnblogs.com/xiefang2008/p/7703716.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值