How can I copy a string to the clipboard within my console application WITHOUT adding a reference to System.Windows.Forms?

Platform invoking the clipboard APIs is a possible solution. Example:

using System.Runtime.InteropServices;
class Program
{
    [DllImport("user32.dll")]
    internal static extern bool OpenClipboard(IntPtr hWndNewOwner);

    [DllImport("user32.dll")]
    internal static extern bool CloseClipboard();

    [DllImport("user32.dll")]
    internal static extern bool SetClipboardData(uint uFormat, IntPtr data);

    [STAThread]
    static void Main(string[] args)
    {
        OpenClipboard(IntPtr.Zero);
        var yourString = "Hello World!";
        var ptr = Marshal.StringToHGlobalUni(yourString);
        SetClipboardData(13, ptr);
        CloseClipboard();
        Marshal.FreeHGlobal(ptr);
    }
}

This is just an example. Adding a little error handling around the code, like checking the return values of the P/Invoke functions, would be a good addition.

SetClipboardData is the interesting bit. You also want to make sure you open and close the clipboard, too.

The 13 passed in as the first argument is the data format. 13 means a Unicode string.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)