Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

OpenFileDialog within visual studio macro

Status
Not open for further replies.

EvilCabal

Programmer
Jul 11, 2002
206
0
0
CA
Hi,

I have a macro in Visual Studio to launch the current project with the proper command line. This command lines holds a file name that I would like the user to select with an open file dialog box but OpenFileDialog fails to work with the following 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. This exception is only raised if a debugger is attached to the process."

Googling this error made me add this line to my sub:
Code:
System.Threading.Thread.CurrentThread.SetApartmentState(System.Threading.ApartmentState.STA)
But now I get a "Failed to set the specified COM apartment state." error. What should I do? All I want is a dialog to select a file within a macro.

Here is the code:
Code:
Public Sub SelectArgs()
Dim openfile As New System.Windows.Forms.OpenFileDialog

openfile.InitialDirectory = "c:\"
openfile.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
openfile.FilterIndex = 2
openfile.RestoreDirectory = True
If openfile.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
[...]
End Sub
Thanks.
 
Can anyone give me a hand on this, I managed to get it to work by adding <System.STAThread()> in front of my sub declaration. However, it worked for about 5 minutes and, without apparent reason, went back to giving error messages... Seriously, what the hell.

Their is really little info on working with dialog box within macros out there.

Thanks.

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top