Last night I was going through some older code I had written and upgrading it from VS 2003 to VS 2005. One particularly simple project was giving me some strange errors when I ran it after upgrading. This particular project is a password generator I had written originally in JavaScript, then VB6, then VS 2003 before finally last night upgrading it to VS 2005. The error I got when I ran the project was:
“The 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.”
Well the only place this error was being raised was any time I worked with the clipboard in my program…for example, when you generate a password and select it from the list, it copies the password to the clipboard for you. It also has an option to manually clear the copied password from the clipboard and finally it empties the clipboard when the program exits…so I thought there must be something odd with the clipboard under VS 2005 and added the <STAThreadAttribute()> around my code.
Much to my dismay, the goofy error still cropped up. I got desperate. I set breakpoints whenever the clipboard was called in my code and still didn’t get any more detail than that original error message. It was getting late so I put it all away until just a little while ago and I though I’d tackle it again with a fresh set of eyes. Turns out at least one other guy in a newsgroup out there had a similar issue with an upgrade project…his solution was to remove an old/unused dll from the projects bin directory and sure enough I cleared those out, did a rebuild and my code worked…just to check things further I removed the <STAThreadAttribute()> and the code still worked.
So here’s a word of warning if you upgrade VS 2003 projects to VS 2005 – go ahead and clear out those bin directories – possibly even before you run the project to save yourself a headache :)