我怎样才能复制一个字符串,在我的控制台应用程序剪贴板而不添加引用System.Windows.Forms的?我的、剪贴板、而不、控制台

2023-09-04 02:05:40 作者:中意你

我有一个.net 4.0控制台应用程序生成SQL并将其存储在一个字符串变量。我想这个字符串直接复制到剪贴板。到目前为止,所有我的研究表明,只有这样,这都不可能做的是通过添加引用System.Windows.Forms的。我不想一个引用到一个组件,它是无关的一个控制台应用程序。

I have a .NET 4.0 console app that generates SQL and stores it in a string variable. I want this string to be copied directly to the clipboard. So far, all my research indicates that the ONLY way this can possibly be done is by adding a reference to System.Windows.Forms. I do not want to add a reference to an assembly that is irrelevant to a console app.

内,其中我们当前存在的宇宙中,是有文本字符串复制到内一个控制台应用程序剪贴板,不涉及增加提及System.Windows.Forms的或任何其他组件,其目的是对公知的方法不相干的一个最基本的控制台应用程序?

Within the universe in which we currently exist, is there a known method of copying a string of text to the clipboard within a console app that does not involve adding a reference to System.Windows.Forms nor any other assembly whose purpose is irrelevant to a bare-bones console application?

推荐答案

平台调用剪贴板API的是一个可能的解决方案。例如:

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

这仅仅是一个例子。加入少许错误处理周围的code,如检查P的返回值/启动功能将是一个很好的补充。

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是有趣的一点,你也想确保你打开和关闭剪贴板了。

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

13 传递的第一个参数是数据格式。 13 意味着单code字符串

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