C#访问剪切板,兼容控制台和web

来源:互联网 发布:手机阅读小说软件 编辑:程序博客网 时间:2024/06/09 23:33

C#访问剪切板有系统封装的方法:

            System.Windows.Clipboard.SetText(text);            System.Windows.Clipboard.GetText();            System.Windows.Forms.Clipboard.SetText(text);            System.Windows.Forms.Clipboard.GetText();

以上2个方法,wpf和winform访问时没问题的,用控制台和web调用时会出问题。

System.Windows.Forms.Clipboard 直接拿不到数据,因为web和控制台不包含窗体,所以窗体下的一切api都不能用,这个就放弃做兼容吧。

System.Windows.Clipboard会报异常

异常信息:

必须先将当前线程设置为单个线程单元(STA)模式方可进行 OLE 调用。

说明:执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。

异常详细信息: System.Threading.ThreadStateException: 必须先将当前线程设置为单个线程单元(STA)模式方可进行 OLE 调用。


这个有的救,改装如下:


    public static class WindowsUtil    {        /// <summary>        /// 复制文本到剪切板        /// </summary>        [STAThread]        public static void SetClipboard(string text)        {            System.Windows.Clipboard.SetText(text);        }        /// <summary>        /// 获取剪切板文本        /// </summary>        [STAThread]        public static string GetClipboard()        {            return System.Windows.Forms.Clipboard.GetText();        }    }


        /// <summary>        /// 复制文本到剪切板        /// </summary>        public static void SetClipboard(string text)        {            Thread th = new Thread(new ThreadStart(delegate()            {                WindowsUtil.SetClipboard(text);            }));            th.TrySetApartmentState(ApartmentState.STA);            th.Start();            th.Join();        }        /// <summary>        /// 获取剪切板文本        /// </summary>        public static string GetClipboard()        {            string text = null;            Thread th = new Thread(new ThreadStart(delegate()            {                text = WindowsUtil.GetClipboard();            }));            th.TrySetApartmentState(ApartmentState.STA);            th.Start();            th.Join();            return text;        }


原创粉丝点击