Product : Engine, Version : 5.0.1.1035, ArticleID : 41023835

HowTo : Unhandled exception error in VC++.NET

Article41023835
TypeHowTo
ProductEngine
Version5.0.1.1035
Date Added1/18/2005
Submitted byMassimo Schinardi
Keywords

Subject

Unhandled exception error in VC++.NET

Summary

An unhandled exception of type 'System.Threading.ThreadStateException' occurred in system.windows.forms.dll

Additional information: Could not instantiate ActiveX control 'd4739fdd-dc16-4ab8-bb0a-469661ccae31' because the current thread is not in a single-threaded apartment.

Solution

In the file form1.cpp where is the main form replace the:

//int APIENTRY _tWinMain(HINSTANCE hInstance,
// HINSTANCE hPrevInstance,
// LPTSTR lpCmdLine,
// int nCmdShow)
//{
// System::Threading::Thread::CurrentThread->ApartmentState = System::Threading::ApartmentState::STA;
// Application::Run(new Form1());
// return 0;
//}

with:

using namespace System::Threading;

public __gc class ThreadWork
{

     public:static void DoWork()
     {
       
Application::Run(new Form1());
     }
};

int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
   ThreadStart* myThreadDelegate =
new ThreadStart(0, &ThreadWork::DoWork);
   Thread* myThread =
new Thread(myThreadDelegate);
   myThread->ApartmentState = System::Threading::ApartmentState::STA;
   myThread->Start();
return 0;
}