How can I get the clipboard text in a non static thread? I have a solution but I'm trying to get the cleanest/shortest way possible. The results turn up as an empty string when calling it normally.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
I would add a helper method that can run an Action as an STA Thread within a MTA Main Thread. I think that is probably the cleanest way to achive it.
class Program
{
[MTAThread]
static void Main(string[] args)
{
RunAsSTAThread(
() =>
{
Clipboard.SetText("Hallo");
Console.WriteLine(Clipboard.GetText());
});
}
/// <summary>
/// Start an Action within an STA Thread
/// </summary>
/// <param name="goForIt"></param>
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();
}
}
回答2:
try adding the ApartmentStateAttribute to your main method
[STAThread]
static void Main() {
//my beautiful codes
}
回答3:
I don't know what your definitions of clean or short are, but if you're willing to use full trust, you can just P/Invoke the native clipboard functions to avoid the threading issues. Here's a complete program to print the text on the clipboard:
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());
}
}
}
回答4:
You can't; you must specify the STAThread
attribute.
Note:
ThreadStateException
The current thread is not in single-threaded apartment (STA) mode. Add the
STAThreadAttribute
to your application's Main method.