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

后端 未结 1 1228
陌清茗
陌清茗 2021-01-23 23:38

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 l

相关标签:
1条回答
  • 2021-01-23 23:59

    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
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题