Search code examples
c#multithreadingtaskclipboard

How to use Clipboard.GetText using a Task?


I'm programming a Windows form application which automates an old software. For transferring information between that software and my application I use Clipboard. Clicking a button on old software puts some information in the clipboard.

For using Clipboard.GetText I should call it from a windows form. But I don't want everything on UI thread.

When calling Clipboard.GetText in another task I got it says you should call Clipboard.GetText from an STAThread.


Solution

  • If you don't want to use neither Windows.Forms or Wpf clipboard, you can invoke native clipboard api, as shown here:

    How can I copy a string to clipboard within my console app WITHOUT adding a reference to System.Windows.Forms?

    Sample for getting string from clipboard

            OpenClipboard(IntPtr.Zero);
    
            var ptr = GetClipboardData(13);
            var s = Marshal.PtrToStringUni(ptr);
            Marshal.FreeHGlobal(ptr);
            CloseClipboard();
    

    i have used 13 as clipboard type (CF_UNICODETEXT) Full list you could see here: https://msdn.microsoft.com/de-de/library/windows/desktop/ff729168(v=vs.85).aspx