0

I use Visual Studio 2005 to develop a "Windows Service" using c#.net. My code requires to access the MS office Clipboard. But on trying to access the Clipboard class, the debugger throws an error

"Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it."

during the run-time. On checking for the solutions, I found that this could be solved by adding "[STAThread]" before the main method. But on adding this, I get a compilation error

"The type or namespace name 'STAThread' could not be found (are you missing a using directive or an assembly reference?)"

Is it possible to access the clipboard with my current version of .NET(.NET 3.0)?

The main method is in a file titled "program.cs" and the logic is in a file titled "Service.cs". Clipboard is used by Service.cs.

/* Program.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            
        }
    }
}

/* Service.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            
        }
    }
}
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445

0 Answers0