Clipboard.GetText returns null (empty string)

You can only access the clipboard from an STA thread. Rick Brewster ran into this with some refactoring of the regular Edit->Paste command, in Paint.NET.

Code:

IDataObject idat = null;
Exception threadEx = null;
Thread staThread = new Thread(
    delegate ()
    {
        try
        {
            idat = Clipboard.GetDataObject();
        }

        catch (Exception ex) 
        {
            threadEx = ex;            
        }
    });
staThread.SetApartmentState(ApartmentState.STA);
staThread.Start();
staThread.Join();
// at this point either you have clipboard data or an exception

Code is from Rick. http://forums.getpaint.net/index.php?/topic/13712-/page__view__findpost__p__226140

Update: Jason Heine made a good point of adding () after delegate to fix the ambiguous method error.

Leave a Comment