我使用 Visual Studio 2005 使用 c#.net 开发“Windows 服务”。我的代码需要访问 MS office 剪贴板。但是在尝试访问 Clipboard 类时,调试器会抛出错误
“在进行 OLE 调用之前,必须将当前线程设置为单线程单元 (STA) 模式。确保您的 Main 函数上标记了 STAThreadAttribute。”
在运行期间。在检查解决方案时,我发现这可以通过在 main 方法之前添加“[STAThread]”来解决。但是在添加这个时,我得到一个编译错误
“找不到类型或命名空间名称‘STAThread’(您是否缺少 using 指令或程序集引用?)”
是否可以使用我当前版本的 .NET(.NET 3.0) 访问剪贴板?
主要方法位于名为“program.cs”的文件中,逻辑位于名为“Service.cs”的文件中。Service.cs 使用剪贴板。
/* 程序.cs */
using System.Collections.Generic;
using System.ServiceProcess;
using System.Text;
using System.Media;
using System.Threading;
namespace WindowsService1
{
static class Program
{
[STAThread]
static void Main(string[] args)
{
#if DEBUG
Service1 serv = new Service1();
serv.onDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new Service1() };
ServiceBase.Run(ServicesToRun);
#endif
}
}
}
/* 服务.cs */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Timers;
namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
public void onDebug()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
clear_cb();
}
protected void clear_cb()
{
Clipboard.Clear(); // This is the line where I get the exception
}
protected override void OnStop()
{
// TODO: To clear the back up Database
}
}
}