Reputation: 169
I am trying to read a file which include some commands that i want to be copied to clipboard. On searching internet i have found a way how to copy data into clipboard which i have done successfully. However i have to copy multiple commands. which i am doing in a while loop. Here is my code.
{
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();
}
}
}
So the problem i found is in the following line Marshal.FreeHGlobal(ptr);
or may be in SetClipboardData(13, ptr);
but i do not know how to resolve this. This runs very fine in the first go but in second or third the program stop responding. Any help will be greatly appreciated.
I am not using windows forms. i am trying to build it in console.
Upvotes: 1
Views: 392
Reputation: 186668
It seems that you don't want all that pInvoke stuff, but Clipboard.SetText
:
using System.Windows.Forms; // to have "Clipboard" class
using System.IO; // to have "File" class
...
class Program {
[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();
}
}
Upvotes: 1