Programming Tips & Tricks

Home Categories: C# | C++ | General | Other

Other Tips & Tricks: Copy&Paste code from Visual Studio as HTML

Thanks to a nice addin, it's possible to to copy & paste source code from Visual Studio 2010 and keep its coloring.
To get the addin, either search for 'Productivity Power Tools' in the extension manager, or go here. (unfortunately this only works if you have a non-free version of VS, since you cannot install extensions in the Express editions).
Now when you copy code inside VS you can paste it into OpenOffice, Wordpad, or some other program, and it looks like it did in VS.

If you want to go a step further and get the actual HTML tags, for example to use on your webpage, like i do here, you can paste into OpenOffice or some word processor, and then export as html, open the html source and copy the relevant code.
But you can make it a bit more streamlined with some code.
All you need is some function to access the clipboard, and specify the mode of access. If you set this to html mode, you will get a complete html document, with html and body tags. The actual content you want is nicely put between two html comments titled 'StartFragment' and 'EndFragment'.
Below is some C# code i use. First it gets the clipboard contents as html. Then it copies the relevant part into a string (and does some error checking) and finally places the result again into the clipboard. The important part is that now the text is placed there in standard text format, not in html format, meaning when you paste it somewhere now, you will get the actual html tags.

void ConvertClipboardText ()
    string start = "<!--StartFragment-->";
    string end = "<!--EndFragment-->";
    string input = Clipboard.GetText(TextDataFormat.Html);
    if (input == null || input == "")

    int index1 = input.IndexOf(start);
    if (index1 < 0) return;
    index1 += start.Length;

    int index2 = input.IndexOf(end);
    if (index2 < 0) return;

    string output = input.Substring(index1, index2 - index1);


I simply put this code into the button handler of a simple form containing just that button. With this i can now simply hit copy in VS, press the button in my app, and paste into an html document.
An additional tip: use Alt-Selection (press ALT, then select some text with the mouse) when you select code inside VS, this way you can select the code without the tabs or spaces on line beginnings of indented code blocks.