Strange behaviour with clipboard in C# console application

.net, c#, clipboard, console, winforms

Solution

Use this function

static string GetMeText()
  {
     string res = "starting value";
     Thread staThread = new Thread(x => 
       {
         try
         {
             res = Clipboard.GetText();
         }
         catch (Exception ex) 
         {
            res = ex.Message;            
         }
       });
    staThread.SetApartmentState(ApartmentState.STA);
    staThread.Start();
    staThread.Join();
    return res;
  }

In this line:

  Console.WriteLine("You copied " + Clipboard.GetMeText());

The problem is that the clipboard only works with certain threading models (ApartmentState.STA) so you have to make a new thread and give it that model this code does that.

Problem

Consider this small program: ``` class Program { [STAThread] static void Main(string[] args) { Console.WriteLine("Please copy something into the clipboard."); WaitForClipboardChange(); Console.WriteLine("You copied " + Clipboard.GetText()); Console.ReadKey(); } static void WaitForClipboardChange() { Clipboard.SetText("xxPlaceholderxx"); while (Clipboard.GetText() == "xxPlaceholderxx" && Clipboard.GetText().Trim() != "") Thread.Sleep(90); } } ``` I run it, and I copy a string from Notepad. But the program just gets an empty string from the clipboard and writes "You copied ". What's the problem here? Is there something that makes clipboard access behave weirdly in a console application? This is Windows 7 SP1 x86, .NET 4 Client Profile.

Original source

Related problems