为什么clipboard.setdataobject不会在C#中将对象复制到剪贴板 [英] Why clipboard.setdataobject doesn't copy object to the clipboard in C#

查看:217
本文介绍了为什么clipboard.setdataobject不会在C#中将对象复制到剪贴板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个win app(C#),它使用剪贴板向/从其他应用程序发送和接收数据。例如,我想在Windows中使用Word应用程序,我使用c#将文本复制到剪贴板,但是当我想在c#中模拟粘贴键(Stroke Ctrl + v)时,剪贴板是空的,我只是得到了v作为结果。

要复制到剪贴板,请使用以下代码:

I have a win app (C#) that use clipboard to send and receive data to/from other applications. for example i wnat to use Word app in windows, I copy a text using c# to the clipboard, but when i want to simulate paste key (Stroke Ctrl+v) in c# , the clipboard is empty and i just got "v" as result.
To copy to the clipboard i use the following code:

public static void CopyToClipboard(string textForCopyToClipBoard)
{
  Clipboard.Clear();
  Clipboard.SetDataObject(
        textForCopyInClipBoard, 
        true, 
        5, 
        200); 
}





要模拟粘贴或描边Ctrl + v,我使用以下代码



To simulate paste or stroke Ctrl+v, i use the following code

public static void PasteFromClipboard()
       {
           System.Windows.Forms.SendKeys.Send("^v");
       }





我尝试过:



要复制到剪贴板,我尝试了以下方法



What I have tried:

To copy to the clipboard, I tried the following method

推荐答案

首先使用Clipboard.SetText而不是SetDataObject - 它应该没有在这种情况下没有任何区别,但这是一种更简单的做事方式。

您的代码有效:我在我的一个应用程序中以简单的形式尝试过:

Start by using Clipboard.SetText instead of SetDataObject - it shouldn't make any difference in this case, but it's a simpler way to do things.
Your code works: I tried it in a simple form in one of my apps:
private void button2_Click(object sender, EventArgs e)
    {
    tbPasteIntoMe.Focus();
    Clipboard.SetText("Hello there!");
    SendKeys.Send("^v");
    }

我的文本框获取字符串Hello there!没有问题。

但是......请记住SendKeys总是发送到Active应用程序 - 这可能属于你的应用程序,而不是你要粘贴的应用程序。这可能与你的问题有关...



但说实话,你不应该使用剪贴板,除非用户明确告诉你 - 很多如果你在没有事先询问的情况下覆盖他们放在剪贴板上的内容,那么用户(包括我)会非常非常恼火。

您可能应该找到更好的进程间通信方法 - 使用剪贴板是我称之为蛮力和无知的方法,通常意味着你的整个设计需要看。

And my textbox gets the string "Hello there!" without problems.
But...do remember that SendKeys always sends to the Active application - which is probably yours, not the one you want to paste into. This may have something to do with your problem...

But to be honest, you shouldn't use the clipboard unless the user has explicitly told you to - many users (including me) will get very, very annoyed if you overwrite what they have placed on the clipboard without asking them in advance.
You probably should find a better method for interprocess communications - using the clipboard is what I call a "brute force and ignorance" approach which generally means your whole design needs looking at.


这篇关于为什么clipboard.setdataobject不会在C#中将对象复制到剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆