我必须将.NET应用程序作为插件包含到另一个.NET应用程序中。插件接口要求我从模板表单继承。然后在加载插件时将表单附加到MDI中。
到目前为止,一切都正常,但是每当我注册拖放事件时,设置组合框或其他各种情况下的自动完成模式,就会得到以下异常:
在进行OLE调用之前,必须将
...the当前线程设置为单线程单元(STA)模式。确保您的主要功能上标记了STAThreadAttribute .
主要应用程序在MTA中运行,由另一家公司开发,所以我对此无能为力。
我试图在STA线程中做一些导致这些异常的事情,但这也没有解决问题。
有没有人遇到过同样的情况?我能做些什么来解决这个问题吗?
发布于 2009-09-08 09:50:33
更新:公司发布了一个新的STA版本。这个问题已不再适用。
发布于 2009-06-30 12:07:55
您可以尝试生成新线程并调用带有0的CoInitialize (分离线程),并在这个线程中运行应用程序。但是,您不需要在这个线程中直接更新控件,您应该在每次修改UI时使用Control.Invoke。
我不知道这会不会成功,但你可以试试。
发布于 2011-02-16 20:44:09
最近,我在试图从网络摄像机中读取图像时遇到了这个问题。最后我做的是创建一个产生新STA线程的方法,在该方法上运行单线程方法。
问题所在
private void TimerTick(object sender, EventArgs e)
{
// pause timer
this.timer.Stop();
try
{
// get next frame
UnsafeNativeMethods.SendMessage(this.captureHandle, WindowsMessageCameraGetFrame, 0, 0);
// copy frame to clipboard
UnsafeNativeMethods.SendMessage(this.captureHandle, WindowsMessageCameraCopy, 0, 0);
// notify event subscribers
if (this.ImageChanged != null)
{
IDataObject imageData = Clipboard.GetDataObject();
Image image = (Bitmap)imageData.GetData(System.Windows.Forms.DataFormats.Bitmap);
this.ImageChanged(this, new WebCamEventArgs(image.GetThumbnailImage(this.width, this.height, null, System.IntPtr.Zero)));
}
}
catch (Exception ex)
{
MessageBox.Show("Error capturing the video\r\n\n" + ex.Message);
this.Stop();
}
}
// restart timer
Application.DoEvents();
if (!this.isStopped)
{
this.timer.Start();
}
}解决方案:将单线程逻辑移动到自己的方法,并从新的STA线程调用此方法。
private void TimerTick(object sender, EventArgs e)
{
// pause timer
this.timer.Stop();
// start a new thread because GetVideoCapture needs to be run in single thread mode
Thread newThread = new Thread(new ThreadStart(this.GetVideoCapture));
newThread.SetApartmentState(ApartmentState.STA);
newThread.Start();
// restart timer
Application.DoEvents();
if (!this.isStopped)
{
this.timer.Start();
}
}
/// <summary>
/// Captures the next frame from the video feed.
/// This method needs to be run in single thread mode, because the use of the Clipboard (OLE) requires the STAThread attribute.
/// </summary>
private void GetVideoCapture()
{
try
{
// get next frame
UnsafeNativeMethods.SendMessage(this.captureHandle, WindowsMessageCameraGetFrame, 0, 0);
// copy frame to clipboard
UnsafeNativeMethods.SendMessage(this.captureHandle, WindowsMessageCameraCopy, 0, 0);
// notify subscribers
if (this.ImageChanged!= null)
{
IDataObject imageData = Clipboard.GetDataObject();
Image image = (Bitmap)imageData.GetData(System.Windows.Forms.DataFormats.Bitmap);
// raise the event
this.ImageChanged(this, new WebCamEventArgs(image.GetThumbnailImage(this.width, this.height, null, System.IntPtr.Zero)));
}
}
catch (Exception ex)
{
MessageBox.Show("Error capturing video.\r\n\n" + ex.Message);
this.Stop();
}
}https://stackoverflow.com/questions/1063181
复制相似问题