所以我对 C++ 有点陌生(到目前为止 4-6 个月 + 从书本上学习(不是老师)),我知道这个问题很可能是我的误解造成的,但在谷歌搜索后我仍然无法弄清楚很多搜索词......我也尝试了stackoverflow并阅读: 跨线程操作无效:控制'Form1'从线程之外的线程访问 跨线程操作无效:控制从其他线程访问比它在 调用任何跨线程代码的最佳方式上创建的线程? 我试图为此创建一个解决方案(您可以在下面看到),但我未能将代码从 c# 转换为 c++(我不是 C# 用户,所以......)我可以用(来自:Crossthread operation无效... - VB.NET):
listView1->CheckForIllegalCrossThreadCalls = false;
但由于这不是一个好习惯,我正在寻找一种替代方法。
当我尝试在我的线程中调用此 clr 代码时:
void CClient::add(){
lvhandle = (HWND)project1::Form1::ClrForm1->listView1->Handle.ToPointer();
/* as you can see here, I tried to figure out how to use MethodInvoker but failed...
if(project1::Form1::ClrForm1->listView1->InvokeRequired){
lvhandle = (HWND)project1::Form1::ClrForm1->listView1->Handle.ToPointer();
//project1::Form1::ClrForm1->listView1->Invoke(gcnew System::Windows::Forms::MethodInvoker(this, &annoyme));
}
else
{
lvhandle = (HWND)project1::Form1::ClrForm1->listView1->Handle.ToPointer();
}*/
item.pszText = LPSTR_TEXTCALLBACK; // Sends an LVN_GETDISPINFO message.
item.mask = LVIF_TEXT | LVIF_IMAGE |LVIF_STATE;
item.stateMask = 0;
item.iSubItem = 0;
item.state = 0;
item.pszText = L"test";
item.lParam = 0;
ListView_InsertItem(lvhandle, &item);
std::string lol = std::to_string(item.iItem);
String^ test;
test = marshal_as<String^>(lol);
project1::Form1::ClrForm1->Text = test;
}
它给了我一个例外:
Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.
ClrForm1 定义为:
public ref class Form1 : public System::Windows::Forms::Form
{
public:
static Form1^ ClrForm1;
我在触发入口点时创建。
int main(array<System::String ^> ^args)
{
// Enabling Windows XP visual effects before any controls are created
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
// Create the main window and run it
Form1::ClrForm1 = gcnew Form1();
Application::Run(Form1::ClrForm1);
return 0;
}
我还通过以下方式确认了错误:
project1::Form1::ClrForm1->Text = "Test!0";
希望我详细说明了这一点以得到回应>。<