首先,一个类里,有个linkLabel1
private OpenFileDialog openFileDialog1;
private DialogResult result;
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
openFileDialog1 = new OpenFileDialog();
string patch = Application.StartupPath + "\\LOG\\";
openFileDialog1.InitialDirectory = patch;
openFileDialog1.Filter = "xls files (*.xls)|*.xls";
result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
if (openFileDialog1.FileName != "")
{
Process.Start(openFileDialog1.FileName);
}
}
}
就会报
在可以调用 OLE 之前,必须将当前线程设置为单线程单元(STA)模式。请确保您的 Main 函数带有 STAThreadAttribute 标记。 只有将调试器附加到该进程才会引发此异常。
在测试小程序里没有问题,当移到大程序里就这样的问题了。可能是线程多的原因。解决办法就是添加线程,代码如下
private Thread invokeThread;
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = patch;
openFileDialog1.Filter = "xls files (*.xls)|*.xls";
invokeThread = new Thread(new ThreadStart(InvokeMethod));
invokeThread.SetApartmentState(ApartmentState.STA);
invokeThread.Start();
invokeThread.Join();
if (result == DialogResult.OK)
{
if (openFileDialog1.FileName != "")
{
Process.Start(openFileDialog1.FileName);
}
}
}
private void InvokeMethod()
{
result = openFileDialog1.ShowDialog();
}
问题得到解决