C# Clipboard 类 SetText 方法报错

发布于 2024-06-19  408 次阅读


温馨提示:本文最后更新于2024年6月19日,已超过 30 天没有更新,某些文章具有时效性,若有错误或已失效,请在下方留言!

问题

C# 内置 Clipboard 类封装了一系列操作剪贴板的方法,一般使用方法:

// For this example, the data to be placed on the clipboard is a simple string.
string textData = "I want to put this string on the clipboard.";

// After this call, the data (string) is placed on the clipboard and tagged
// with a data format of "Text".
Clipboard.SetData(DataFormats.Text, (Object)textData);

但是由于其他程序占用(特别是迅雷),实际上在进行 Clipboard.SetData() 操作时经常出现如下错误:
引发的异常:“System.Runtime.InteropServices.COMException”(位于 System.Private.CoreLib.dll 中)
Error in CopyLine: OpenClipboard 失败 (0x800401D0 (CLIPBRD_E_CANT_OPEN))

解决方法

使用 WinAPI 进行复制操作。新建类 ClipboardSetText ,代码如下:

using System;
using System.Runtime.InteropServices;

namespace Utilities
{
    internal class ClipboardSetText
    {
        [DllImport("User32")]
        public static extern bool OpenClipboard(IntPtr hWndNewOwner);

        [DllImport("User32")]
        public static extern bool CloseClipboard();

        [DllImport("User32")]
        public static extern bool EmptyClipboard();

        [DllImport("User32")]
        public static extern bool IsClipboardFormatAvailable(int format);

        [DllImport("User32")]
        public static extern IntPtr GetClipboardData(int uFormat);

        [DllImport("User32", CharSet = CharSet.Unicode)]
        public static extern IntPtr SetClipboardData(int uFormat, IntPtr hMem);

        public static void SetText(string text)
        {
            if (!OpenClipboard(IntPtr.Zero))
            {
                SetText(text);
                return;
            }
            EmptyClipboard();
            SetClipboardData(13, Marshal.StringToHGlobalUni(text));
            CloseClipboard();
        }
    }
}

使用 ClipboardSetText.SetText() 即可。

参考

Clipboard 类 (System.Windows) | Microsoft Learn

C#-Clipboard类SetText方法失效报错的问题解决_clipboard.settext-CSDN博客

最后更新于 2024-06-19