Search code examples
c#copy-paste

Simulate Control+v key press when creating a txt file


Hello everyone and thank you in advance.

I have copied a text and now I want to paste this text into a ".txt" what needs to be created automatically. I know the paste simulation key is as follows:

System.Windows.Forms.SendKeys.Send("^{v}");

On the other hand, the previous simulation key press should be included somehow within the following code (which creates a writes), but I am not sure how to do this...

public void writeTXT()
{
    if (!File.Exists(path))
    {
        using (StreamWriter sw = File.CreateText(path))
        {
           sw.WriteLine();
        }
     }
}

Any comments will be welcome! Thanks a lot.


Solution

  • You don't have to simulate keypresses. You can access the clipboard directly:

    using (StreamWriter sw = File.CreateText(path))
    {
       sw.WriteLine(Clipboard.GetText());
    }