如何在非静态线程中获取剪贴板文本?我有一个解决方案,但我正在尝试获得最干净/最短的方式。正常调用时,结果显示为空字符串。
发布于 2011-05-10 13:31:21
我会添加一个帮助器方法,它可以在MTA主线程中将Action作为STA线程运行。我认为这可能是实现它的最干净的方式。
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();
}
}发布于 2011-05-10 11:54:15
尝试将ApartmentStateAttribute添加到main方法中
[STAThread]
static void Main() {
//my beautiful codes
}发布于 2011-05-10 13:16:23
我不知道你对clean或short的定义是什么,但如果你愿意使用完全信任,你可以只调用本机剪贴板函数来避免线程问题。下面是一个在剪贴板上打印文本的完整程序:
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());
}
}
}https://stackoverflow.com/questions/5944605
复制相似问题