Search code examples
c#winformsclipboardcopy-pasteclipboarddata

How do I copy text to the clipboard with partial italics?


How do I make it so that txtTitleofWebpage.Text is in italics when copied to the Clipboard so that the user can copy the references into a Microsoft Word document? I'm trying to make a Windows Form Application using C# to generate Harvard References from information the user inputs into a form.

Here is the code:

Clipboard.SetText(wholeName + ", (" + yOPDate + ") " + txtTitleofWebpage.Text + 
                  " [online]. Available from: " + txtURLWeb.Text + " [Accessed: " + 
                  accessDateWeb.Value.ToShortDateString() + "].", TextDataFormat.Rtf);

Solution

  • It seems you have to insert a 'header' in the html string, I found 2 examples for this:

    This works with Word:
    Example code:

        Clipboard.SetText(@"Version:1.0
                            StartHTML:000125
                            EndHTML:000260
                            StartFragment:000209
                            EndFragment:000222
                            <HTML>
                            <head>
                            <title>HTML clipboard</title>
                            </head>
                            <body>
                            <!–StartFragment–><b>Hello!</b><!–EndFragment–>
                            </body>
                            </html>", 
                            TextDataFormat.Html);
    

    This copies a Hello! to your clipboard, you have to change the fragments based on the size I think so I don't know exactly how that would work with a dynamic string but I hope this will get you started. 666

    If you can also use RTF

    Clipboard.SetText(@"{\rtf1\ansi This is in \i\f0\fs17 italic\i0.}",
                        TextDataFormat.Rtf);
    

    Example with string

    var q = "test123";
    Clipboard.SetText(@"{\rtf1\ansi This is in \i\f0\fs17 " + q + @"\i0.}",
                        TextDataFormat.Rtf);
    

    or

    var q = "test123";
    Clipboard.SetText( $@"{\rtf1\ansi This is in \i\f0\fs17 {q}\i0.}",
                        TextDataFormat.Rtf);
    

    Note the @ before the 2nd part of the string, if you need to escape certain characters (you will need that with RTF) add @ in front of each opening ".

    This seems to be a lot easier because you don't have to insert the header but the formatting itself is abit more complicated imo.