c# - Clipboard.GetImage() 返回 null

标签 c# winforms clipboard

我有一个 DataGridView,其中包含一个 Image 列和一些文本列。我有一个非常简单的处理程序,允许用户从单元格中复制文本或图像并将图像和文本粘贴到其中。复制/粘贴在文本上工作正常,但粘贴在图像上不起作用。 (注意:如果我粘贴从另一个应用程序(如画图)放置在剪贴板上的图像,则它可以正常工作)

如果我在 Clipboard.SetImage() 之后立即调用 Clipboard.GetImage() 它工作正常,这让我相信它可能是范围问题或者 Clipboard 正在抓取一个引用而不是图像中的底层字节。我必须将原始图像字节放在共享位置吗?我检查了 MSDN definition for GetImage以确保我做得正确。

    private void dataGridView_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control)
        {
            if (Clipboard.ContainsImage())
            {
                Image img = Clipboard.GetImage();  // always returns null

                if (cell.ColumnIndex == _imageCol)
                    cell.Value = img;
            }

            if (Clipboard.ContainsText())
            {
                if (cell.ColumnIndex != _imageCol)
                    cell.Value = Clipboard.GetText(); // always works
            }
        }

        if (e.KeyCode == Keys.C && e.Modifiers == Keys.Control)
        {
            DataGridViewCell cell = dataGridView1.SelectedCells[0];

            if (cell.ColumnIndex == _imageCol)
            {
                Clipboard.SetImage((Image)cell.Value);
                Image img2 = Clipboard.GetImage();  // successfully returns the Image
            }
            else
                Clipboard.SetText((string)cell.Value);
        }
    }

最佳答案

您没有指望的是 DataGridView 实现了复制/粘贴。使用与您使用的相同的快捷键,Ctrl+C 和 Ctrl+V。所以看起来它在您将图像放在剪贴板上后就可以工作,但 DGV 也会这样做并覆盖剪贴板内容。不幸的是,它不复制图像,只复制文本。图像列的空字符串。

你必须告诉它你处理了击键:

    private void dataGridView1_KeyDown(object sender, KeyEventArgs e) {
        if (e.KeyCode == Keys.V && e.Modifiers == Keys.Control) {
            // etc...
            e.Handled = true;
        }

        if (e.KeyCode == Keys.C && e.Modifiers == Keys.Control) {
            // etc...
            e.Handled = true;
        }
    }

关于c# - Clipboard.GetImage() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32461845/

相关文章:

c# - 来自 C# 的多个更新和插入

c# - 在 datepicker c# Winforms 上引发验证事件

javascript - 将剪贴板中的图像粘贴到fabric.js Canvas 上?

JavaScript 在粘贴事件上获取剪贴板数据(跨浏览器)

c# - 选择多个文件和文件夹所需的对话框 .NET

c - 剪贴板内存的本地副本?

c# - 如何使按钮不显示但仍被javascript使用?

c# - 保护 DLL 不被我自己以外的其他项目使用

c# - 保存状态的选项

c# - 如何获取屏幕的显示深度?