字符串复制到剪贴板错误

本文关键字:错误 剪贴板 复制 字符串 | 更新日期: 2023-09-27 18:24:12

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

{
    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);行或者可能在CCD_ 2中,但我不知道如何解决这个问题。这在第一次运行时运行得很好,但在第二次或第三次运行时程序停止响应。任何帮助都将不胜感激。

我没有使用windows窗体。我正试图在控制台中构建它

字符串复制到剪贴板错误

似乎你不想要所有pInvoke的东西,但Clipboard.SetText:

using System.Windows.Forms; // to have "Clipboard" class
using System.IO;            // to have "File" 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();
    }
}