一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

ShowDialog() 错误的解决

时间:2022-11-14 22:02:54 编辑:袖梨 来源:一聚教程网

showdialog() 错误的解决

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();
}

问题得到解决

热门栏目