Populating Clipboard from Console App

As part of creating a SQL Server CLR function (other posts to come) I needed to copy the output of a command line app to the clipboard. Now I could of course simply redirect the text to a file and then open the file in Notepad++ and do a Ctrl-A Ctrl-C and go, but that offended my command-line sensibilities. So instead I wrote a short console application that takes standard in and copies it to the clipboard.

To say the code is trivial would be an understatement, it's a one-line program. However I did discover that if I didn't set the main function to be STA threaded I couldn't access the clipboard. This makes sense to me since the clipboard access is via COM and COM doesn't like non-STA things.


Like I said, simple code. We set the clipboard data to a text format copy of everything in the stdin stream.

Usage is simple too, just pipe what you want on the clipboard into the program. For example, want a directory listing of c:\ in the clipboard, do this:

dir c:\ | clipboard


Or as another post will show, want the hex representation of a DLL on the clipboard? Do this

AsHex < TheFile.dll | clipboard


You will need add a reference to PresentationCore to get access to the System.Windows namespace. And remember, just because it's a PresentationCore function doesn't mean you need to be in WPF or WinForms to use it.

1 comment:

  1. I think it will be really useful one to handle samall applications and clipboards. I am soon going to try this out.

    ReplyDelete