C#Clipboard.GetText()

如何在非静态线程中获取剪贴板文本? 我有一个解决方案,但我正在努力获得最干净/最短的方式。 在正常调用时,结果会变为空字符串。

我将添加一个辅助方法,可以在MTA主线程中将Action作为STA线程运行。 我认为这可能是实现它的最简洁方法。

class Program { [MTAThread] static void Main(string[] args) { RunAsSTAThread( () => { Clipboard.SetText("Hallo"); Console.WriteLine(Clipboard.GetText()); }); } ///  /// Start an Action within an STA Thread ///  ///  static void RunAsSTAThread(Action goForIt) { AutoResetEvent @event = new AutoResetEvent(false); Thread thread = new Thread( () => { goForIt(); @event.Set(); }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); @event.WaitOne(); } } 

尝试将ApartmentStateAttribute添加到main方法中

 [STAThread] static void Main() { //my beautiful codes } 

我不知道你对clean或short的定义是什么,但是如果你愿意使用完全信任,你可以只需P / Invoke本机剪贴板函数来避免线程问题。 这是一个在剪贴板上打印文本的完整程序:

 using System; using System.Runtime.InteropServices; namespace PasteText { public static class Clipboard { [DllImport("user32.dll")] static extern IntPtr GetClipboardData(uint uFormat); [DllImport("user32.dll")] static extern bool IsClipboardFormatAvailable(uint format); [DllImport("user32.dll", SetLastError = true)] static extern bool OpenClipboard(IntPtr hWndNewOwner); [DllImport("user32.dll", SetLastError = true)] static extern bool CloseClipboard(); [DllImport("kernel32.dll")] static extern IntPtr GlobalLock(IntPtr hMem); [DllImport("kernel32.dll")] static extern bool GlobalUnlock(IntPtr hMem); const uint CF_UNICODETEXT = 13; public static string GetText() { if (!IsClipboardFormatAvailable(CF_UNICODETEXT)) return null; if (!OpenClipboard(IntPtr.Zero)) return null; string data = null; var hGlobal = GetClipboardData(CF_UNICODETEXT); if (hGlobal != IntPtr.Zero) { var lpwcstr = GlobalLock(hGlobal); if (lpwcstr != IntPtr.Zero) { data = Marshal.PtrToStringUni(lpwcstr); GlobalUnlock(lpwcstr); } } CloseClipboard(); return data; } } class Program { static void Main(string[] args) { Console.WriteLine(Clipboard.GetText()); } } } 

你不能; 您必须指定STAThread属性 。

注意:

ThreadStateException

当前线程不是单线程单元(STA)模式。 将STAThreadAttribute添加到应用程序的Main方法中。