Can not round trip html format to clipboard

2019-08-01 08:45发布

问题:

I want to write Html format, but I can not even get a simple MSDN example of it to work.

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

Does this console app, a clipboard round tripper, work for anyone?

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();
    }
}

回答1:

When you copy data from a browser onto the clipboard, it puts the same data onto the clipboard in multiple formats, including both text and HTML. So you can read the data back out in either text or HTML format. However, when you call SetText here, you are ONLY passing in HTML format, so when you use the regular GetText, there is no text version on the clipboard and you get null back.

You can put multiple formats onto the clipboard at once (i.e., both text and HTML) using IDataObject, but you have to do the translation between formats yourself before you put the data on the clipboard. There's an example of how to use IDataObject here.



回答2:

I can reproduce that it doesn't work... the var text2 = Clipboard.GetText(); returns "" each time...

(edit) A quick search yields this, which seems on topic.