0

I am trying to get a copy to clipboard in my .ascx file. Since this is ASP.NET, there is no main function to put [STAThread] on.

I am getting an error stating: "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."

In my ascx.cs file I have using System.Windows.Forms; and then one line of code Clipboard.SetText("Hello, clipboard");

I've attempted to find a solution, but most solutions assume that there is a main, or say to delete dlls. These solutions are not fit for my situation.

emmajean
  • 25
  • 1
  • 1
  • 7
  • 1
    I'm not 100 % certain, but still reasonably sure that you cannot change an ASP.NET worker thread to STA. Anyway, the apartment mode cannot be changed once a thread is running. But you could always start a new STA `Thread`; and set its apartment mode to STA just before you `.Start()` it; and execute your OLE-using code on that thread. – stakx - no longer contributing Feb 10 '15 at 22:42
  • How do I do this then? before I use `Clipboard.SetText` do I call STAThreadAttribute? Where do I put .Start() in this case? – emmajean Feb 10 '15 at 22:53
  • stakx is how I would approach this STA problem with the thought that I would be creating a new thread. I am not sure how you control the first CoCreate thread in an IIS process so that may get you in the end. **HOWEVER** I can not imagine ANY scenario where I would be copying between threads in a multithreaded service app like IIS using the Clipboard. You would have multiple threads reading and writing to the wrong data. There are many other ways to do IPC Interprocess Communication and Same Process Communication such as Cache objects and unique pointers to session databases – Sql Surfer Feb 10 '15 at 22:58
  • I changed my code to the following: `var thread = new Thread(() => Clipboard.SetText("Hello, clipboard")); thread.SetApartmentState(ApartmentState.STA); thread.Start();` And am no longer getting an error, however it is not copying the text to the clickboard. – emmajean Feb 10 '15 at 23:04
  • Your approach seems to be inside the server. Look at the answer in this question. It solves the problem in the browser. http://stackoverflow.com/questions/17527870/how-does-trello-access-the-users-clipboard – Sql Surfer Feb 10 '15 at 23:06
  • possible duplicate of [How do I copy to the clipboard in JavaScript?](http://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – mason Feb 10 '15 at 23:10

1 Answers1

2

You are following the wrong approach. You're thinking about this from a server side perspective, but you can't access a user's clipboard from the server side. You can however do it from JavaScript running on the client. But that's a different question, and it's already been answered.

Community
  • 1
  • 1
mason
  • 31,774
  • 10
  • 77
  • 121