VC CLR工程中加入了webbrowser控件,運行後報“當前線程不在單線程單元中”錯誤。
解決辦法:
#include "stdafx.h"
#include "MyForm.h"
#include <iostream>
#include <stdlib.h>
#include <combaseapi.h>
#pragma comment(lib,"Ole32.lib")
using namespace System;
using namespace ConsoleApplication3;
int main(array<System::String ^> ^args)
{
CoUninitialize();
HRESULT hr = CoInitialize(NULL);
if (hr != S_OK)
printf("hr failed/n");
else
printf("hr ok/n");
MyForm frm;
frm.ShowDialog();
return 0;
}
原理就是調用了CoInitialize(NULL),創建並進入一個單線程單元。類似於c#的 [STAThread] void main(....)
直接調用CoInitialize有可能會返回錯誤,所以要在前面加一條CoUninitialize()。
百試百靈,以上。