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

只谈情不闲聊 提交于 2020-01-11 11:29:47

问题


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();

回答1:


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
            }
        }
    }
}


来源:https://stackoverflow.com/questions/51444458/c-sharp-clipboard-returns-null-but-cant-be-empty

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!