Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Clipboard.GetText()

Tags:

c#

clipboard

How can I get the clipboard text in a non static thread? I have a solution but I'm trying to get the cleanest/shortest way possible. The results turn up as an empty string when calling it normally.

like image 1000
Drake Avatar asked May 10 '11 02:05

Drake


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is C full form?

Full form of C is “COMPILE”. One thing which was missing in C language was further added to C++ that is 'the concept of CLASSES'.

What language is C in?

C is a procedural language that provides no support for objects and classes. C++ is a combination of OOP and procedural programming languages. C has 32 keywords and C++ has 63 keywords. C supports built-in data types, while C++ supports both built-in and user-defined data types.


2 Answers

I would add a helper method that can run an Action as an STA Thread within a MTA Main Thread. I think that is probably the cleanest way to achive it.

class Program
{
    [MTAThread]
    static void Main(string[] args)
    {
        RunAsSTAThread(
            () =>
            {
                Clipboard.SetText("Hallo");
                Console.WriteLine(Clipboard.GetText());
            });
    }

    /// <summary>
    /// Start an Action within an STA Thread
    /// </summary>
    /// <param name="goForIt"></param>
    static void RunAsSTAThread(Action goForIt)
    {
        AutoResetEvent @event = new AutoResetEvent(false);
        Thread thread = new Thread(
            () =>
            {
                goForIt();
                @event.Set();
            });
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        @event.WaitOne();
    }
}
like image 176
BitKFu Avatar answered Oct 25 '22 17:10

BitKFu


try adding the ApartmentStateAttribute to your main method

[STAThread]
static void Main() {
  //my beautiful codes
}
like image 33
Rejinderi Avatar answered Oct 25 '22 17:10

Rejinderi