C# Clipboard in Console Application

发现在控制台应用程序中无法获得剪贴板中的数据。

查看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;
}


猜你喜欢

转载自blog.csdn.net/wangyue4/article/details/39431725