c# Clipboard returns null, but can't be empty

2020-04-30 11:40发布

I am trying to get a link which was generated on click and pasted in my clipboard. I tried everything I could find. But I always recieve "null", even though when I paste the link manually in a notepad and what not, I get it.

I tried this code with every defined Dataformat, but everything returned null.

string clipboardText = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();

标签: c# clipboard
1条回答
做个烂人
2楼-- · 2020-04-30 12:31

From MSDN: To use this class, ensure that your Main method is marked with the STAThreadAttribute attribute.

Example:

using System.Windows.Forms;  // Need this for console app
namespace ClipboardTest
{
    class Program
    {
        // Without this attribute, will get null
        [STAThreadAttribute]
        static void Main(string[] args)
        {
            try
            {
                var clipboardText = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();
                Console.WriteLine(clipboardText);
            }
            catch (NullReferenceException ex1)
            {
                // Handle error
            }
            catch (System.Threading.ThreadStateException ex2)
            {
                // Will throw this when:
                // "The current thread is not in single-threaded apartment (STA) mode and the Application.MessageLoop property value is true."
                // Handle error
            }
            catch (System.Runtime.InteropServices.ExternalException ex3)
            {
                // Will throw this if clipboard in use
                // Handle error
            }
        }
    }
}
查看更多
登录 后发表回答