字符串复制到剪贴板错误

String copying to clipboard error

我正在尝试读取一个文件,其中包含一些我想复制到剪贴板的命令。在搜索互联网时,我找到了一种将数据复制到剪贴板的方法,我已经成功完成了。但是我必须复制多个命令。这是我在 while 循环中做的。这是我的代码。

{
    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)
        {
            int counter = 0;
            string line;
            // Read the file and display it line by line.
            System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Users\st4r8_000\Desktop\office work\checks documents\interface check commands.txt");
            OpenClipboard(IntPtr.Zero);
            //int x;
            while((line = file.ReadLine()) != null)
            {
                Console.WriteLine (line);

                //clip board copier

                var yourString = line;
                var ptr = Marshal.StringToHGlobalUni(yourString);
                SetClipboardData(13, ptr);

                Marshal.FreeHGlobal(ptr);
                Console.ReadLine();
                //end of clip board copier
                counter++;
                //ptr = x;

            }
            CloseClipboard();
            file.Close();
            // Suspend the screen.
            Console.ReadLine();
        }
    }
}

所以我发现的问题在下面一行Marshal.FreeHGlobal(ptr); 或者可能在 SetClipboardData(13, ptr); 但我不知道如何解决这个问题。这在第一次运行时运行良好,但在第二次或第三次程序停止响应。任何帮助将不胜感激。

我没有使用 windows 表格。我正在尝试在控制台中构建它。

看来您并不想要所有 pInvoke 东西,但是 Clipboard.SetText:

using System.Windows.Forms; // to have "Clipboard" class
using System.IO;            // to have "File" class

   ...

class 程序 {

    [STAThread]
    static void Main(string[] args)
    {
        var lines = File.ReadLines(@"C:\Users\st4r8_000\Desktop\office work\checks documents\error log check.txt");

        StringBuilder clipBuffer = new StringBuilder();

        foreach (String line in lines)
        {
            Console.WriteLine(line);

            if (clipBuffer.Length > 0)
                clipBuffer.Append('\n');

            clipBuffer.Append(line);
            Clipboard.SetText(line);
            // Incremental addition; 
            // Clipboard.SetText(line); 
            // if new line should superecede the old one
            //Clipboard.SetText(clipBuffer.ToString());

            Console.ReadLine();
        }
        // Suspend the screen.
        Console.ReadLine();
    }
}