代码之家  ›  专栏  ›  技术社区  ›  jyoung

无法将html格式往返剪贴板

  •  3
  • jyoung  · 技术社区  · 17 年前

    我想写Html格式,但我甚至无法得到一个简单的MSDN示例。

    http://msdn.microsoft.com/en-us/library/tbfb3z56.aspx

    这个控制台应用程序,一个剪贴板往返器,对任何人都有效吗?

    using System;
    using System.Windows; //Need to add a PresentationCore or System.Windows.Forms reference
    
    class Program {
        [STAThread]
        static void Main( string[] args ) {
            Console.WriteLine( "Copy a small amount of text from a browser, then press enter." );
            Console.ReadLine();
    
            var text = Clipboard.GetText();
            Console.WriteLine();
            Console.WriteLine( "--->The clipboard as Text:" );
            Console.WriteLine( text );
    
            Console.WriteLine();
            Console.WriteLine( "--->Rewriting clipboard with the same CF_HTML data." );
            //***Here is the problem code***
            var html = Clipboard.GetText( TextDataFormat.Html );
            Clipboard.Clear();
            Clipboard.SetText( html, TextDataFormat.Html );
    
            var text2 = Clipboard.GetText();
            Console.WriteLine();
            Console.WriteLine( "--->The clipboard as Text:" );
            Console.WriteLine( text2 );
    
            var isSameText = ( text == text2 );
            Console.WriteLine();
            Console.WriteLine( isSameText ? "Success" : "Failure" );
    
            Console.WriteLine();
            Console.WriteLine( "Press enter to exit." );
            Console.ReadLine();
        }
    }
    
    2 回复  |  直到 17 年前
        1
  •  3
  •   Eric Rosenberger    17 年前

    当您将数据从浏览器复制到剪贴板时,它会将相同的数据以多种格式(包括文本和HTML)放入剪贴板。因此,您可以以文本或HTML格式读取数据。但是,当你在这里调用SetText时,你只是以HTML格式传递,所以当你使用常规GetText时,剪贴板上没有文本版本,你会得到null。

    您可以使用ViewModel Object一次将多种格式(即文本和HTML)放入剪贴板,但在将数据放入剪贴板之前,您必须自己进行格式之间的转换。这里有一个如何使用ViewModel Object的示例 here .

        2
  •  0
  •   Marc Gravell    17 年前

    我可以复制它不起作用 var text2 = Clipboard.GetText(); 返回 "" 每次。..

    (编辑) 快速搜索得到 this ,这似乎是主题。