您的位置:首页 > 移动开发

C# Clipboard in Console Application

2014-09-20 14:35 288 查看
发现在控制台应用程序中无法获得剪贴板中的数据。

查看msdn有提到

The Clipboard class can only be used in threads set to single thread apartment (STA) mode. To use this class, ensure that your Main method is marked with the STAThreadAttribute attribute.

所以最终的解决方案如下:

public static object GetClipboardData()
{
object ret = null;
ThreadStart method = delegate()
{
System.Windows.Forms.IDataObject dataObject = Clipboard.GetDataObject();
if (dataObject != null && dataObject.GetDataPresent(DataFormats.Text))
{
ret = dataObject.GetData(DataFormats.Text);
}
};
if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
{
Thread thread = new Thread(method);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
}
else
{
method();
}
return ret;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: